0%

19. Remove Nth Node From End of List

O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(next = head)
slow, fast = dummy, head
for _ in range(n):
fast = fast.next
while fast:
slow, fast = slow.next, fast.next
slow.next = slow.next.next
return dummy.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy_head = 0;
dummy_head.next = head;
auto fast = head, slow = &dummy_head; // slow指向head的前一个,这样最后slow指向要删的node的前一个,方便删除,比如[1]删倒数第1
while (n-- > 0) {
fast = fast->next;
}
while (fast) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummy_head.next;
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy_head = 0;
dummy_head.next = head;
auto fast = head, slow = &dummy_head;
while (fast) {
fast = fast->next;
if (--n < 0) {
slow = slow->next;
}
}
slow->next = slow->next->next;
return dummy_head.next;
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
ListNode dummy_head(0);
dummy_head.next = head;
ListNode *fast = head;
while (n-- > 0 && fast) {
fast = fast->next;
}
if (n >= 0) return head; // 要考虑链表长度不足n
ListNode *slow = head, *prev = &dummy_head;
while (fast) {
prev = prev->next;
slow = slow->next;
fast = fast->next;
}
prev->next = slow->next;
return dummy_head.next;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr)
return head;
auto front(head);
auto behind(&head);
while (front) {
front = front->next;
if (--n < 0)
behind = &(*behind)->next;
}
auto to_be_deleted(*behind);
*behind = (*behind)->next;
delete to_be_deleted;
return head;
}
};