【发布时间】:2021-12-29 04:38:09
【问题描述】:
给定两个排序的链表,结果应该是无重复的并集。
- 不允许创建新节点。
- 结果列表将由原始列表的元素组成。
输入是由空行分隔的两个列表:
L1 -> 2 3 3 4 4 4 5
L2 -> 3 4 5 5 6 7
结果 -> 2 3 4 5 6 7
我在下面有我的解决方案,但在 Union 函数中创建新节点。
有没有什么简单的方法可以改变Union函数的逻辑,不创建任何新节点并删除重复项?
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
def PrintLinkedList( p ):
print( "Result:", end=" " )
while p!=None:
print( p.data, end=" " )
p = p.next
print(".")
def ReadLinkedList():
first = None
last = None
r = input()
while r!="":
row = r.split()
if len(row)==0:
break
for s in row:
p = Node(int(s),None)
if first==None:
first = p
else:
last.next = p
last = p
r = input()
return first
def dedup(head):
current = head
while current:
runner = current
# Check, until runner.next is not None.
while runner.next:
if current.data == runner.next.data:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
def Union(a, b):
# A dummy node to store the result
dummyNode = Node(0)
headA = a
headB = b
# Tail stores the last node
tail = dummyNode
while True:
# If any of the list gets completely empty
# directly join all the elements of the other list
if headA is None:
tail.next = headB
break
if headB is None:
tail.next = headA
break
# Compare the x of the lists and whichever is smaller is
# appended to the last of the merged list and the head is changed
if headA.data <= headB.data:
tail.next = headA
headA = headA.next
else:
tail.next = headB
headB = headB.next
# Advance the tail
tail = tail.next
# Delete dups and returns the head of the merged list
dedup(dummyNode.next)
return dummyNode.next
【问题讨论】:
-
您可以在合并时重用任何列表的节点。而不是创建新节点,只需使用两个列表中的任何一个节点。因为根据任务,您可以修改给定的列表,因此可以将它们的节点用于/修改用于您需要的任何目的。
标签: python python-3.x algorithm linked-list singly-linked-list