Leetcode-19. 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.
- 本题可以利用快慢指针的方法来解决,让快指针先走n步,然后快指针和慢指针同时走,当快指针到达终点时,慢指针指向的就是我们要删除的节点了。
- 删除的节点的方式可以用多种表示,如若想删除1和3之间的2节点,可以有如下几种表示
node1->next = node3; node1->next = node2->next; node1->next = node1->next->next;
- 还可以这样表示:
解决方法一ListNode **del = &node2; *del = (*del)->next;
解决方法二:引入一个哑节点dummy,让快指针先走n+1步。struct ListNode { int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; class Solution { public: ListNode * removeNthFromEnd(ListNode* head, int n) { ListNode **del = &head, *iter = head; for (int i = 0; i < n; ++i, iter = iter->next); for (; iter != NULL; del = &((*del)->next), iter = iter->next); *del = (*del)->next; return head; } };
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode first = dummy; ListNode second = dummy; for (int i = 1; i <= n + 1; i++) { first = first.next; } while (first != null) { first = first.next; second = second.next; } second.next = second.next.next; return dummy.next; }