1. 程式人生 > 實用技巧 >LeetCode 19 刪除連結串列的倒數第N個節點

LeetCode 19 刪除連結串列的倒數第N個節點

LeetCode 19 刪除連結串列的倒數第N個節點

問題描述:
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。

雙指標

  • 兩指標間剛好間隔N個節點

執行用時:0 ms, 在所有 Java 提交中擊敗了100.00%的使用者
記憶體消耗:36.3 MB, 在所有 Java 提交中擊敗了98.82%的使用者

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) {
            return head;
        }
        
        ListNode p1 = head, p2 = head;
        int curr = 0;
        while(curr<n) {
            p2 = p2.next;
            curr++;
            if(p2==null) {
                //倒數第n個節點為頭節點
                if(curr==n) {
                    return head.next;
                }
                //連結串列長度小於n
                else {
                    return head;
                }
            }
        }

        while(p2.next!=null) {
            p1 = p1.next;
            p2 = p2.next;
        }

        ListNode tmp = p1.next;
        p1.next = tmp.next;
        tmp.next = null;

        return head;
    }
}