Remove Nth Node From End of List 解答

Question

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.

Solution -- One pass

Use two pointers, slow and fast. Fast pointer firstly move n steps. Then, when fast pointer reaches end, slow pointer reaches the node before deleted node.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         ListNode fast = head, slow = head;
12         if (head == null)
13             return head;
14         while (n > 0) {
15             fast = fast.next;
16             n--;
17         }
18         // If remove the first node
19         if (fast == null) {
20             head = head.next;
21             return head;
22         }
23         while (fast.next != null) {
24             fast = fast.next;
25             slow = slow.next;
26         }
27         slow.next = slow.next.next;
28         return head;
29     }
30 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4812038.html