1. 程式人生 > >刪除鏈表的倒數第N個節點

刪除鏈表的倒數第N個節點

定位 bubuko end turn div png tno 返回 com

給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。

示例:

給定一個鏈表: 1->2->3->4->5, 和 n = 2.

當刪除了倒數第二個節點後,鏈表變為 1->2->3->5.

一種方法是先計算鏈表的長度N,然後定位到第(N-n)個節點,刪除節點(N-n+1)也即(倒數第n個節點)

代碼如下:

    public static ListNode removeNthFromEnd(ListNode head, int n) {

        // 新建一個節點temp
        // temp.next = head可以保存鏈表的頭結點
        
// 也方便處理刪除的是第一個節點(倒數第N個) ListNode temp = new ListNode(0); temp.next = head; int N = 0; // Get the length of the list while (head != null) { N++; head = head.next; } N = N-n; head = temp; // Locate the (N-n)th node
while (N>0) { head = head.next; N--; } head.next = head.next.next; return temp.next; }

第二種方法是,使用兩個指針,首先將第一個指針置於第二個的後n+1個節點處。再同時移動兩個指針,當第一個指向鏈表末尾時,第二個指針指向第(N-n)個節點。

以n=2為例,即刪除倒數第二個節點

技術分享圖片

指針2指向開始處,指針1與指針2相隔為(n+1)

技術分享圖片

同時移動指針1與2,當1指向null時,二指向倒數第(n+1)個節點。

代碼如下:

    public static ListNode test(ListNode head, int n) {
        ListNode temp = new ListNode(0);
        temp.next = head;
        ListNode p = temp;
        ListNode q = temp;
        while (n+1>0) {
            q = q.next;
            n--;
        }
        while (q != null) {
            p = p.next;
            q = q.next;
        }
        p.next = p.next.next;
        return temp.next;
    }

刪除鏈表的倒數第N個節點