"""
已知两个链表head1和head2各自有序(例如升序排列),请把他们合并成一个链表,要求合并后的链表依然有序。
"""
class LNode:
def __init__(self):
self.data = None
self.next = None
def ConstructList(start):
"""
方法功能:构造链表
:param start:
:return:
"""
i = start
head = LNode()
tmp = None
cur = head
while i < 7:
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 2
return head
def PrintList(head):
cur = head.next
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
def Merge(head1, head2):
"""
方法功能:合并两个升序排列的单链表
:param head1: 链表1
:param head2: 链表2
:return: 合并后链表的头结点
"""
if head1 is None or head1.next is None:
return head2
if head2 is None or head2.next is None:
return head1
cur1 = head1.next # 用来遍历head1
cur2 = head2.next # 用来遍历head2
head = None # 合并后链表的头结点
cur = None # 合并后的链表在尾结点
# 合并后链表的头结点为第一个结点元素最小的那个链表的头结点
if cur1.data > cur2.data:
head = head2
cur = cur2
cur2 = cur2.next
else:
head = head1
cur = cur1
cur1 = cur1.next
# 每次找到链表剩余结点最小值对应的结点连接到合并后链表的尾部
while cur1 is not None and cur2 is not None:
if cur1.data < cur2.data:
cur.next = cur1
cur = cur1
cur1 = cur1.next
else:
cur.next = cur2
cur = cur2
cur2 = cur2.next
# 当遍历完一个链表后把另外一个链表剩余结点连接到合并后的链表后边
if cur1 is not None:
cur.next = cur1
if cur2 is not None:
cur.next = cur2
return head
if __name__ == '__main__':
head1 = ConstructList(1)
head2 = ConstructList(2)
print('head1:')
PrintList(head1)
print('\nhead2:')
PrintList(head2)
print('\n合并后的链表')
head = Merge(head1, head2)
PrintList(head)
运行j结果如下:
head1:
1 3 5
head2:
2 4 6
合并后的链表
1 2 3 4 5 6
6080

被折叠的 条评论
为什么被折叠?



