Given A linked list, remove the n-th node from the end of the list and return its head.
Example:
N = 2.After Removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Follow up:
Could do I in one pass?
AC Code:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {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, 1, 2, 2, 3, 4, 5demo:0, 3--------4--- /slow: /Step2:5fast, 1, 2, 4, 3, 2, 3, 5demo:0, 1-- C4/>/slow: /step3:1, 2, 3, 4, 5demo:0, 1--2---3-- 5f AST: /slow: /step4: 1, 2, 3, 4, 5demo:0, 1, 2, 3 4, 5fast: /slow: /Step5:fast->next = = Nullslow->next = Slow->n ext->next; 1, 2, 3, 4, 5demo:0, 1, 2, 3--- 5fast: | /|slow: | | |_______|
Remove Nth Node from End of List