【題目描述】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.
【算法思路】這道題的關鍵在於找倒數第n個結點的前驅結點:可以設置慢行指針slow和快行指針fast,讓快行指針fast先走n步,然後同步地移動慢行指針slow和快行指針fast,這樣它們之間的距離永遠相差n個結點,當fast指針移動最後一個結點的時候,slow指向倒數第n個結點;
【編程步驟】
* 1. 處理特殊情況:如果被移除的結點爲頭結點,則移除,並返回第二個結點作爲頭結點;
* 2. 如果爲其他情況,則找到倒數第n個結點的前驅結點 pre;
* 3. 移除倒數第n個結點,即 pre.next=slow.next
或
pre.next=pre.next.next ;
【代碼實現】
/**
* 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) {
if(head==null)
return null;
ListNode fast=head;
int step=0;
while(step<n&&fast!=null){
step++;
fast=fast.next;
}
// the removed node is the head
if(fast==null){
return head.next;
}
ListNode pre=head;
ListNode slow=head;
// find the positon of the removed node , the slow node
while(fast!=null){
pre=slow;
slow=slow.next;
fast=fast.next;
}
// remove the node
pre.next=slow.next;
return head;
}
}