我用Python编写了一个函数来合并两个排序的链表。这是代码:-
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next is not None:
last_node = last_node.next
last_node.next = new_node
def print(self):
cur_node = self.head
while cur_node.next is not None:
print(cur_node.data, "-> ", end='')
cur_node = cur_node.next
print(cur_node.data)
def merge(l1, l2):
cur_node1 = l1.head
cur_node2 = l2.head
l3 = LinkedList()
while cur_node1.next is not None or cur_node2.next is not None:
if cur_node1.data > cur_node2.data:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
else:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
if cur_node1.next is None:
l3.append(cur_node1.data)
while cur_node2.next is not None:
l3.append(cur_node2.data)
cur_node2 = cur_node2.next
l3.append(cur_node2.data)
elif cur_node2.next is None:
l3.append(cur_node2.data)
while cur_node1.next is not None:
l3.append(cur_node1.data)
cur_node1 = cur_node1.next
l3.append(cur_node1.data)
return l3
ll1 = LinkedList()
ll2 = LinkedList()
ll1.append(12)
ll1.append(45)
ll1.append(69)
ll1.append(70)
ll2.append(1)
ll2.append(2)
ll2.append(99)
ll2.append(100)
ll3 = merge(ll1, ll2)
ll3.print()
这里发生了什么?我不明白。我尝试在合并函数的 while 循环中运行没有 or 语句的代码。效果很好。显然问题出在 while 语句中。有人可以帮忙吗?
冉冉说
素胚勾勒不出你
青春有我
相关分类