1. 程式人生 > >19. Remove Nth Node From End of List (雙指標)

19. Remove Nth Node From End of List (雙指標)

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個節點,當快指標的下一個元素為空就說明慢指標的下一個節點應該刪除。

注意:

1. 如果連結串列本來就只有一個節點,刪除之後就是空,所以不能返回head,而是應該new一個新的節點指向head,返回新節點的next;

 public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode sta = new ListNode(0);
        ListNode slow = sta;
        ListNode fast = sta;
        slow.next = head;
        for(int i=0;i<n;i++)
            fast = fast.next;
        while(fast.next!=null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return sta.next;
    }