LeetCode_Everyday:019 Remove Nth Node From End of List

LeetCode_Everyday:019 Remove Nth Node From End of List


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

給定一個鏈表,刪除鏈表的倒數第n個節點,並且返回鏈表的頭結點。
進階:你能嘗試使用一趟掃描實現嗎?

示例:

  • 示例 1:
    給定一個鏈表: 1->2->3->4->5, 和 n = 2.
    當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
    

代碼

方法一: 遞歸 題解

執行用時:32 ms, 在所有 Python3 提交中擊敗了98.09%的用戶
內存消耗:13.5 MB, 在所有 Python3 提交中擊敗了5.41%的用戶

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        global i   
        if head is None:
            i=0
            return None
        head.next = self.removeNthFromEnd(head.next,n)
        i+=1
        return head.next if i==n else head

"""
For Example:    input:    1->2->3->4->5, 和 n = 2
               output:    1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
                
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('輸出爲:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))

方法二: 快慢指針 題解

執行用時:48 ms, 在所有 Python3 提交中擊敗了35.30%的用戶
內存消耗:13.7 MB, 在所有 Python3 提交中擊敗了5.41%的用戶

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        dummy.next = head
        fast,slow = dummy,dummy
        for  i in range(n+1):
            fast = fast.next
        while fast is not None: 
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

"""
For Example:    input:    1->2->3->4->5, 和 n = 2
               output:    1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
                
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('輸出爲:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))

參考

  1. https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/python-di-gui-by-adamch0u/
  2. https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/guan-fang-ti-jie-de-python3-shi-xian-fu-ya-jie-dia/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

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