Python程式:刪除連結串列中所有值為特定值的節點
假設我們有一個單鏈表和一個目標值,我們需要刪除所有值為目標值的節點後返回該連結串列。
例如,如果輸入是 [5,8,2,6,5,2,9,6,2,4],那麼輸出將是 [5, 8, 6, 5, 9, 6, 4]
為了解決這個問題,我們將遵循以下步驟:
- head := node
- 當 node 和 node.next 不為空時,執行以下操作:
- 當 node 的 next 節點的值等於目標值時,執行以下操作:
- node.next := node.next.next
- node := node.next
- 當 node 的 next 節點的值等於目標值時,執行以下操作:
- 如果 head 的值等於目標值,則:
- 返回 head.next
- 否則:
- 返回 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
while (node and node.next):
while node.next.val == target:
node.next = node.next.next
node = node.next
if head.val == target:
return head.next
else:
return head
ob = Solution()
head = make_list([5,8,2,6,5,2,9,6,2,4])
ob.solve(head, 2)
print_list(head)輸入
[5,8,2,6,5,2,9,6,2,4]
輸出
[5, 8, 6, 5, 9, 6, 4, ]
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP