leetcode: Remove Nth Node From End of List
http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
思路:
两个指针p1和p2,令p2先走N - 1步,然后两个指针一起往前走,每一步保存当前的p1为prev,当p2->next为NULL时,p1就是要删除的那个节点,另prev->next = p1->next。实现的时候比较偷懒,没有考虑输入head为NULL和n为0的情况。
1 class Solution { 2 public: 3 ListNode *removeNthFromEnd(ListNode *head, int n) { 4 ListNode *l1 = head, *l2 = head, *prev = NULL; 5 6 for (int i = 1; i < n; ++i) { 7 l2 = l2->next; 8 } 9 10 while (true) { 11 if (NULL == l2->next) { 12 break; 13 } 14 15 prev = l1; 16 l1 = l1->next; 17 l2 = l2->next; 18 } 19 20 if (prev != NULL) { 21 prev->next = l1->next; 22 return head; 23 } 24 else { 25 return l1->next; 26 } 27 } 28 };