用 Python 编写的删除链接列表中重复条目的程序
pythonserver side programmingprogramming更新于 2026/2/2 15:08:17
假设我们有一个数字链接列表,我们必须删除链接列表中多次出现的数字(在输出中只保留一次出现),我们还必须保持原始链接列表中出现的顺序。
因此,如果输入为 [2 -> 4 -> 6 -> 1 -> 4 -> 6 -> 9],则输出将是 [2 -> 4 -> 6 -> 1 -> 9]。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 node 不为空,则
- l := a new set
- temp := node
- 将 temp 的值插入 l
- 当 temp 的下一个不为空时,执行
- 如果 temp 的下一个值不在 l 中,则
- 将 temp 的下一个值插入 l
- temp := next of temp
- 否则,
- next of temp := next of next of temp
- 如果 temp 的下一个值不在 l 中,则
- return node
让我们看看下面的实现以便更好地理解 −
示例
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):
if node:
l = set()
temp = node
l.add(temp.val)
while temp.next:
if temp.next.val not in l: l.add(temp.next.val)
temp = temp.next
else:
temp.next = temp.next.next
return node
ob = Solution()
head = make_list([2, 4, 6, 1, 4, 6, 9])
print_list(ob.solve(head))
输入
[2, 4, 6, 1, 4, 6, 9]
输出
[2, 4, 6, 1, 9, ]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

