用python定义Node类和单链表类已知两个单链表a 和b 节点值为整数链表中节点按升序排列线编写代码将二者合并并输出所有单链表的元素。
# 定义节点类
class Node:
def __init__(self, val):
self.val = val
self.next = None
# 定义单链表类
class LinkedList:
def __init__(self):
self.head = None
def add(self, val):
node = Node(val)
if self.head is None:
self.head = node
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = node
def merge(self, b):
a_curr = self.head
b_curr = b.head
merged_list = LinkedList()
while a_curr is not None and b_curr is not None:
if a_curr.val < b_curr.val:
merged_list.add(a_curr.val)
a_curr = a_curr.next
else:
merged_list.add(b_curr.val)
b_curr = b_curr.next
while a_curr is not None:
merged_list.add(a_curr.val)
a_curr = a_curr.next
while b_curr is not None:
merged_list.add(b_curr.val)
b_curr = b_curr.next
return merged_list
def print_list(self):
curr = self.head
while curr is not None:
print(curr.val, end=" ")
curr = curr.next
# 示例代码
a = LinkedList()
a.add(1)
a.add(3)
a.add(5)
print("链表a: ", end="")
a.print_list()
b = LinkedList()
b.add(2)
b.add(4)
b.add(6)
print("\n链表b: ", end="")
b.print_list()
merged_list = a.merge(b)
print("\n合并后的链表: ", end="")
merged_list.print_list()
``
原文地址: https://www.cveoy.top/t/topic/eQ75 著作权归作者所有。请勿转载和采集!