19. Remove Nth Node From End of List [easy] (Python)

題目鏈接

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

題目原文

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個節點,並返回鏈表頭部。
比如:給定鏈表1->2->3->4->5,以及 n = 2 , 刪除節點後,鏈表變成 1->2->3->5。
注意:給定的n總是有效的;儘量在一遍遍歷的情況下完成這道題。

思路方法

思路一

用兩個指針,一個指針p從前到後掃描整個鏈表,一個指針q慢指針p的步數爲n+1,那麼當p指向尾部的Null時,指針q恰好指向要刪除節點的前一個節點。由於可能刪除頭部節點,僞裝一個新的頭部方便操作。

代碼

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        new_head = ListNode(0)
        new_head.next = head
        fast = slow = new_head
        for i in range(n+1):
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return new_head.next

思路二

題目並沒有說不能修改節點的值,一個比較tricky的做法是:將倒數第n個節點前的節點的值依次後移,最後返回head.next即爲所求。用遞歸實現了“倒着數”的操作。

代碼

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        def getIndex(node):
            if not node:
                return 0
            index = getIndex(node.next) + 1
            if index > n:
                node.next.val = node.val
            return index
        getIndex(head)
        return head.next

思路三

類似思路二,不過這次不再修改節點值,而是真正的刪除倒數第n個節點。

代碼

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        def remove(node):
            if not node:
                return 0, node
            index, node.next = remove(node.next)
            next_node = node if n != index+1 else node.next
            return index+1, next_node
        ind, new_head = remove(head)
        return new_head

PS: 新手刷LeetCode,新手寫博客,寫錯了或者寫的不清楚還請幫忙指出,謝謝!
轉載請註明:http://blog.csdn.net/coder_orz/article/details/51691267

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章