LeetCode: Remove Nth Node From End of List 解题报告

时间:2021-10-02 04:55:24

Remove Nth Node From End of List

Total Accepted: 46720 Total Submissions: 168596My Submissions

Question Solution 

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.

Show Tags
 

SOLUTION 1:

1.使用快慢指针,快指针先行移动N步。用慢指针指向要移除的Node的前一个Node.

2. 使用dummy node作为head的前缀节点,这样就算是删除head也能轻松handle啦!

主页君是不是很聪明呀? :)

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//
ListNode dummy = new ListNode();
dummy.next = head; ListNode slow = dummy;
ListNode fast = dummy; // move fast N more than slow.
while (n > ) {
fast = fast.next;
// Bug 1: FORGET THE N--;
n--;
} while (fast.next != null) {
fast = fast.next;
slow = slow.next;
} // Slow is the pre node of the node which we want to delete.
slow.next = slow.next.next; return dummy.next;
}
}

GITHUB (国内用户可能无法连接):

https://github.com/yuzhangcmu/LeetCode/blob/251766ffb832f2278f43a05e194ca76584bf14ea/list/RemoveNthFromEnd.java