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?
题意: 删除链表倒数第N个节点
Solution1: Two Pointers(fast and slow)
1. Let fast pointer to move n steps in advance, making sure there is n steps gap between fast and slow
2. Move fast and slow pointer together until fast.next == null
code
1 /* 2 Time: O(n) 3 Space: O(1) 4 */ 5 class Solution { 6 public ListNode removeNthFromEnd(ListNode head, int n) { 7 ListNode dummy = new ListNode(-1); 8 dummy.next = head; 9 ListNode slow = dummy, fast = dummy; 10 11 for (int i = 0; i < n; i++) // fast先走n步 12 fast = fast.next; 13 14 while(fast.next != null) { // fast和slow一起走 15 slow = slow.next; 16 fast = fast.next; 17 } 18 //直接避开要删除的节点 19 slow.next = slow.next.next; 20 return dummy.next; 21 } 22 }
[leetcode]19. Remove Nth Node From End of List删除链表倒数第N个节点
原文:https://www.cnblogs.com/liuliu5151/p/10659178.html