合并两个排序后的链表后,None被附加在新构建的链表的末尾



Node类用于创建节点和链表打印,merge2LinkLists方法是辅助函数。

我正在对每个列表进行迭代和检查,以确保两个排序的链表都被合并为一个新列表。

class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
self.tail = None
def printLinkList(self):
curr = self.head
while(curr):
print(curr.data, end=" ")
curr = curr.next

def addLast(self,value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return
else:
head = self.head
while(head.next):
head = head.next
head.next = new_node
def merge2LinkedList(self,l1,l2):
mergedList = LinkedList()
head1 = l1.head
head2 = l2.head
while(head1 != None and head2 !=None):
if(head1.data < head2.data):
mergedList.addLast(head1.data)
head1 = head1.next
else:
mergedList.addLast(head2.data)
head2 = head2.next
while(head1 != None):
mergedList.addLast(head1.data)
head1 = head1.next
while (head2 != None):
mergedList.addLast(head2.data)
head2 = head2.next
print(mergedList.printLinkList())

list = LinkedList()
list.addLast(2)
list.addLast(4)
list.addLast(5)
list.addLast(6)
list.addLast(90)
list2 = LinkedList()
list2.addLast(3)
list2.addLast(7)
list2.addLast(40)
list2.addLast(45)
list2.addLast(80)
list.merge2LinkedList(list,list2)

输出:

2 3 4 5 6 7 40 45 80 90 None

您正在打印printLinkList的返回值,即None

class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print(self):
curr = self.head
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
def add(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
head = self.head
while head.next:
head = head.next
head.next = new_node
def merge_linked_lists(l1, l2):
merged_list = LinkedList()
head1 = l1.head
head2 = l2.head
while head1 is not None and head2 is not None:
if head1.data < head2.data:
merged_list.add(head1.data)
head1 = head1.next
else:
merged_list.add(head2.data)
head2 = head2.next
while head1 is not None:
merged_list.add(head1.data)
head1 = head1.next
while head2 is not None:
merged_list.addLast(head2.data)
head2 = head2.next
list = LinkedList()
list.add(2)
list.add(4)
list.add(5)
list.add(6)
list.add(90)
list2 = LinkedList()
list2.add(3)
list2.add(7)
list2.add(40)
list2.add(45)
list2.add(80)
merged_list = merge_linked_lists(list, list2)
merged_list.print()

相关内容

  • 没有找到相关文章

最新更新