Leetcode#19 Remove nth node from end of list
Published:
Link:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
Idea:
Fast and slow pointer
Solution:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* slow_pre = NULL;
while (n > 1) {
fast = fast->next;
n--;
}
while(fast->next != NULL) {
fast = fast->next;
slow_pre = slow;
slow = slow->next;
}
if (slow_pre == NULL) {
ListNode* slow_next = slow->next;
slow->next = NULL;
return slow_next;
} else {
slow_pre->next = slow->next;
return head;
}
}
};