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.(意思是O(n)複雜度)
代碼:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//新建一個節點指向head
ListNode behindhead = new ListNode(0);
behindhead.next = head;
//建兩個指針,指針ahead一個指向head節點
ListNode ahead = head;
//指針behind指向behindhead節點
ListNode behind = behindhead;
//指針ahead需要向前移動n-1步
for(int i=0; i<n-1; i++){
if(ahead.next!=null){
ahead = ahead.next;
}
}
//當指針ahead沒有到達尾部時,指針ahead和behind都往前移動
while(ahead.next!=null){
ahead = ahead.next;
behind = behind.next;
}
//刪除behind後面的節點
behind.next = behind.next.next;
return behindhead.next;
}
}