Python程式:移除連結串列中給定目標元素的最後一次出現


假設我們有一個單鏈表,還有一個名為target的值,我們需要移除連結串列中target的最後一次出現。

例如,如果輸入是[5,4,2,6,5,2,3,2,4,5,4,7],target = 5,則輸出將是[5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7]

為了解決這個問題,我們將遵循以下步驟:

  • head := 節點
  • k := null, prev := null
  • found := False
  • 當節點不為空時,執行以下操作:
    • 如果節點的值與target相同,則:
      • found := True
      • prev := k
    • k := node
    • node := node 的下一個節點
  • 如果found為False,則:
    • 返回head
  • 如果prev為空,則:
    • 返回head的下一個節點
  • prev的下一個節點 := prev的下一個節點的下一個節點
  • 返回head

讓我們看看下面的實現來更好地理解:

示例

即時演示

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
   ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
   ptr = ptr.next
   print(']')
class Solution:
   def solve(self, node, target):
      head = node
      k = None
      prev = None
      found = False
      while node:
         if node.val == target:
            found = True
         prev = k
         k = node
         node = node.next
         if found == False:
            return head
         if not prev:
            return head.next
            prev.next = prev.next.next
      return head
ob = Solution()
L = make_list([5,4,2,6,5,2,3,2,4,5,4,7])
target = 5
print_list(ob.solve(L, target))

輸入

[5,4,2,6,5,2,3,2,4,5,4,7]

輸出

[5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7, ]

更新於:2020年11月19日

321 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.