用 Python 编写的程序,删除链表中所有值相同的节点
pythonserver side programmingprogramming更新于 2026/1/10 18:52:17
假设我们有一个单链表和一个目标,在删除所有值与目标相同的节点后,我们必须返回相同的链接。
因此,如果输入为 [5,8,2,6,5,2,9,6,2,4],则输出为 [5, 8, 6, 5, 9, 6, 4, ]
为了解决这个问题,我们将遵循以下步骤 −
- head := node
- 当 node 和 node.next 不为空时,执行
- 当节点的下一个值与目标相同时,执行
- 节点的下一个 := 下一个的下一个节点
- 节点 := 节点的下一个节点
- 当节点的下一个值与目标相同时,执行
- 如果 head 的值与目标相同,则
- 返回 head 的下一个节点
- 否则,
- 返回 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, ]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

