LeetCode 19:刪除鏈表的倒數第N個節點 Remove Nth Node From End of List

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

Given a linked list, remove the n-th node from the end of list and return its head.node

示例:python

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

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

說明:this

給定的 n 保證是有效的。指針

Note:code

Given n will always be valid.rem

進階:it

你能嘗試使用一趟掃描實現嗎?io

Follow up:class

Could you do this in one pass?

解題思路:

這道題頗有意思,雖然很簡單,可是很考驗一我的的思惟。最早想到的方法就是遍歷整個鏈表獲得長度,減去 n 獲得實際應該刪除的節點的位置了。然而因爲單鏈表刪除操做的特殊性,獲得位置以後仍然須要再遍歷一次來刪除該節點。

進階要求是一次遍歷完成該題,想一想是否有好的方法?

假設鏈表長度爲 L ,定義一個指針先走 n 步,此時該指針還剩下 L-n 個節點便可完成該鏈表的遍歷。而第 L-n 個節點不就是題目要求的的要刪除的倒數第 n 個節點嗎?這時候只須要再定義一個指針,讓它與以前的指針同時遍歷,當第一個指針遇到空節點時(null 節點),該指針即指向刪除的節點。

值得注意的的是,指向應當刪除的節點並沒有法刪除它,應當指向該刪除節點的前一個節點。

Java:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode curA = head;
        ListNode curB = head;
        for (int i = 0; i < n; i++) curA = curA.next;
        if (curA == null) {//若是走了n步以後該節點指向空節點,則該鏈表只有一個節點
            head = head.next;
            return head;
        }
        while (curA.next != null) {//當第一個指針的下一個節點爲空時,該指針指向最後一個節點,而指針curB 走了L-n-1步,即指向該刪除節點的前一個節點
            curA = curA.next;
            curB = curB.next;
        }
        curB.next = curB.next.next;//將原本指向應當刪除節點地址指向應當刪除節點的下一個節點的地址
        return head;
    }
}

Python3:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        curA,curB=head,head
        for i in range(n):
            curA=curA.next
        if not curA:
            head=head.next
            return head
        while(curA.next):
            curA=curA.next
            curB=curB.next
        curB.next=curB.next.next

歡迎關注公.衆號一塊兒刷題:愛寫Bug

愛寫Bug.png

相關文章
相關標籤/搜索