1. 程式人生 > >演算法36--Remove Nth Node From End of List

演算法36--Remove Nth Node From End of List

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

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.

給定單鏈表,刪除倒數第n個節點。

基本思路:遍歷一遍獲取連結串列總長度,獲取倒數第n個的正序位置seq,維護兩個指標pre,node找到第seq位置,然後將

pre.next=node.next即可。這裡要注意邊界條件,seq==1,刪除第一個節點,直接返回head.next即可。

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if head==None:
            return head       
        count = 0
        node=head
        while node!=None:
            count += 1
            node = node.next
        seq = count - n + 1
        if seq == 1:
            return head.next
        pre = None
        node = head
        while seq>1:
            pre = node
            node = node.next
            seq -= 1
        pre.next = node.next
        node = None
        return head

Could you do this in one pass?

利用雙指標來定位倒數第n個節點位置,假設連結串列長度為l,第一個指標先移動n,然後第二個指標從頭開始,第一個指標從n開始,這樣當第一個到達尾部時,第二個即為倒數第n個,然後執行刪除操作即可。

以12345  n=2  為例   

第一個指標移動兩步到達2位置

第二個指標從1出發,第一個指標從2出發,當第一個指標到達最後一個元素5時,此時第二個指標指向4,利用pre指標刪除節點4即可

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if head==None:
            return head       
        pre = None
        first = head
        second = head
        while n-1>=1:
            n -= 1
            first = first.next        
        while first.next!=None:
            first = first.next
            pre = second
            second = second.next
        if second==head:
            return head.next
        pre.next = second.next
        return head

大神的程式碼,差不多:

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if n == 0:
            return head
        it = p = head
        i = 0
        while it:
            it = it.next
            i += 1
            if i > n+1:
                p = p.next
        if n == i:
            head = head.next
        else:
            p.next = p.next.next
        return head