19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
AC code:
/** * 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* demo = new ListNode(0); demo->next = head; ListNode* fast = demo; ListNode* slow = demo; for (int i = 0; i < n; ++i) { fast = fast->next; } while (fast->next) { slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return demo->next; } };
Runtime: 8 ms, faster than 34.35% of C++ online submissions for Remove Nth Node From End of List.
step1: 1 -> 2 -> 3 -> 4 -> 5 demo: 0 -> 1 -> 2 -> 3 -> 4 -> 5 fast: /\ slow: /\ step2: 1 -> 2 -> 3 -> 4 -> 5 demo: 0 -> 1 -> 2 -> 3 -> 4 -> 5 fast: /\ slow: /\ step3: 1 -> 2 -> 3 -> 4 -> 5 demo: 0 -> 1 -> 2 -> 3 -> 4 -> 5 fast: /\ slow: /\ step4: 1 -> 2 -> 3 -> 4 -> 5 demo: 0 -> 1 -> 2 -> 3 -> 4 -> 5 fast: /\ slow: /\ step5: fast->next == null slow->next = slow->next->next; 1 -> 2 -> 3 -> 4 -> 5 demo: 0 -> 1 -> 2 -> 3 4 -> 5 fast: | /|\ slow: | | |_______|
永远渴望,大智若愚(stay hungry, stay foolish)