【发布时间】:2021-11-13 22:54:12
【问题描述】:
给定两个排序的链表,结果应该是没有重复的交集。
- 不允许创建新节点。
- 结果列表将由原始列表的元素组成。
输入是由空行分隔的两个列表:
L1 -> 2 3 3 4 4 4 5
L2 -> 3 4 5 6 7
结果 -> 3 4 5
我在下面有我的解决方案,但是在 IntersectionDestruct 函数中创建了新节点。
有没有什么简单的方法可以改变IntersectionDestruct函数的逻辑,不创建任何新节点?
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 LLIntersection(a, b):
head = tail = None
while a and b:
if a.data == b.data:
if head is None:
head = Node(a.data, head)
tail = head
else:
tail.next = Node(a.data, tail.next)
tail = tail.next
a = a.next
b = b.next
# advance the smaller list
elif a.data < b.data:
a = a.next
else:
b = b.next
return head
【问题讨论】:
-
请修正代码的缩进,例如,在第 2 行。
标签: python-3.x algorithm linked-list