19. Remove Nth Node From End of List

LeetCode medium original: C# #csharp #leetcode #linked-list #medium #search
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.
given заголовок связанного списка, удалите n-й узел из конца списка и return его заголовок.

C# solução

correspondente/original
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        int length = 0;
        ListNode curr = head;
        
        // Find the length of the linked list
        while (curr != null) {
            length++;
            curr = curr.next;
        }
        
        int traverseTill = length - n - 1;
        curr = head;
        
        // Traverse to the node before the one to be removed
        for (int i = 0; i < traverseTill; i++) {
            curr = curr.next;
        }
        
        // Remove the nth node from the end
        if (traverseTill == -1) {
            return head.next;
        } else {
            curr.next = curr.next.next;
            return head;
        }
    }
}

C++ solução

rascunho automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
class Solution {
public:
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        int length = 0;
        ListNode curr = head;
        
        // Find the length of the linked list
        while (curr != null) {
            length++;
            curr = curr.next;
        }
        
        int traverseTill = length - n - 1;
        curr = head;
        
        // Traverse to the node before the one to be removed
        for (int i = 0; i < traverseTill; i++) {
            curr = curr.next;
        }
        
        // Remove the nth node from the end
        if (traverseTill == -1) {
            return head.next;
        } else {
            curr.next = curr.next.next;
            return head;
        }
    }
}

Java solução

correspondente/original
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode fast = dummy;
        ListNode slow = dummy;

        // Move fast pointer n steps ahead
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        // Move both pointers until fast reaches the end
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }

        // Remove the nth node from the end
        slow.next = slow.next.next;

        return dummy.next;
    }
}

JavaScript solução

correspondente/original
/
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
    const dummy = new ListNode(0, head);
    let fast = dummy,
        slow = dummy;
    while (n--) {
        fast = fast.next;
    }
    while (fast.next) {
        slow = slow.next;
        fast = fast.next;
    }
    slow.next = slow.next.next;
    return dummy.next;
};

Python solução

correspondente/original
# class ListNode:
#     def init(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head.next == None:
            return None
        tmp = head
        size = 0
        
        # find the size of the linked list
        while tmp:
            size += 1
            tmp = tmp.next
        tmp = head
        
        #if we have to remove the first node:
        if n == size: 
            return head.next
        
        for i in range(size-n-1):
            tmp = tmp.next
        tmp.next = tmp.next.next
        return head

Go solução

correspondente/original
func removeNthFromEnd(head *ListNode, n int) *ListNode {
    dummy := &ListNode{Next: head}
    lead, cur := dummy, dummy

    for i := 0; i <= n; i++ {
        lead = lead.Next
    }

    for lead != nil {
        lead = lead.Next
        cur = cur.Next
    }

    cur.Next = cur.Next.Next
    return dummy.Next
}

Инициализация переменных:

i — счетчик для отслеживания количества узлов, начиная с начала списка.

cur — указатель, начинающийся с головы списка, используется для прохода по списку.

prev — указатель, инициализированный как null. Он используется для отслеживания предыдущего узла, когда cur проходит по списку.

Проход по списку:

Цикл while продолжается до тех пор, пока cur не станет null (то есть пока не достигнут конец списка).

В теле цикла сначала проверяется, достиг ли счетчик i значения n. Если да, prev будет указывать на узел, который находится n узлов перед текущим узлом, или на саму голову списка, если i меньше n.

Затем i увеличивается, а cur перемещается к следующему узлу.

Удаление узла:

Если prev остается null, это означает, что нужно удалить первый узел (голову списка). returnsся следующий узел после головы (

head.next

).

Если prev не null и его следующая ссылка (

prev.next

) существует, эта ссылка обновляется, чтобы пропустить следующий узел (

prev.next

=

prev.next.next

).

Возвращение нового списка:

Если узел был успешно удален, функция returns голову списка. В случае удаления первого узла, returnsся новый начальный узел, иначе returnsся исходный список.

Временная и пространственная Complexity:

Временная Complexity: O(L), где L — длина списка. Функция проходит по всем узлам списка один раз.

Пространственная Complexity: O(1). Используется фиксированное количество дополнительных переменных, независимо от размера Entradaного списка.

Vacancies for this task

vagas ativas with overlapping task tags are mostradas.

Todas as vagas
Ainda não há vagas ativas.