LeetCode19. Remove Nth Node From End of List

題目

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.

結點定義如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */


思路

這個問題的核心就在於只遍歷一次,如果允許兩次則很好解決、先第一遍遍歷知道鏈表長度、第二遍就直接除去倒數第N個結點了。

只遍歷一次我們就想,遍歷結束的標誌就是指向爲空、從指向爲空的結點往前數N個點即爲目標結點,也就是說目標結點與結束標誌相差爲N,那麼我們就可以設置兩個指針p和q,中間相差爲N,兩個指針同步向後走,那麼p(假設在前面)指向爲空的時候,那麼q就自然爲目標指針了,剩下就完成刪除結點的操作。


代碼

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = new ListNode(0);
        ListNode q = p;
        ListNode result = p;
        p.next = head;
        
        for(int i = 0 ; i <= n ; ++ i){
            p = p.next;
        }
        
        while(p != null){
            p = p.next;
            q = q.next;
        }
        
        q.next = q.next.next;
        return result.next;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章