【LeetCode-面試演算法經典-Java實現】【019-Remove Nth Node From End of List(移除單鏈表的倒數第N個節點)】,removenode

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【019-Remove Nth Node From End of List(移除單鏈表的倒數第N個節點)】,removenode
【019-Remove Nth Node From End of List(移除單鏈表的倒數第N個節點)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  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.

題目大意

  刪除單鏈表的倒數第N個結點,注意:輸入的N都是合法,在一次遍曆中完成操作。

解題思路

  先讓一個指標走找到第N個節點,然後再讓一個指標指向頭結點,然後兩具指標一起走,直到前一個指標直到了末尾,後一個指標就是倒數第N+1個結點,刪除倒數第N個結點就可以了。

代碼實現

鏈表結點類

public class ListNode {    int val;    ListNode next;    ListNode(int x) {        val = x;        next = null;    }}

演算法實作類別

public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode pa = head;        ListNode pb = head;        // 找到第n個結點        for (int i = 0; i < n && pa != null; i++) {            pa = pa.next;        }        if (pa == null) {            head = head.next;            return head;        }        // pb與pa相差n-1個結點        // 當pa.next為null,pb在倒數第n+1個位置        while (pa.next != null) {            pa = pa.next;            pb = pb.next;        }        pb.next = pb.next.next;        return head;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/46997239】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.