[LeetCode] Remove Nth Node From End of List

19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

  • new solution update 2022.02.13
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* tail = head;
for(int i = 0; i < n; i++) {
tail = tail->next;
}
ListNode* dummy = new ListNode(-1,head);
ListNode* prev = dummy;
while(tail) {
prev = prev->next;
tail = tail->next;
}
prev -> next = prev->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
27
28
29
30
31
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* tail = head;
ListNode* target = head;
while(n--) {
tail = tail->next;
}
if(tail == nullptr) {
return head -> next;
}

while(tail->next != nullptr) {
target = target->next;
tail = tail->next;
}
target->next = target->next->next;

return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/10/PS/LeetCode/remove-nth-node-from-end-of-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.