# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
merge_next = None
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
if pHead1.val > pHead2.val:
merge_next = pHead2
pHead2 = pHead2.next
merge_next.next = self.Merge(pHead1, pHead2)
else:
merge_next = pHead1
pHead1 = pHead1.next
merge_next.next = self.Merge(pHead1, pHead2)
return merge_next
if __name__ == "__main__":
double_list = input()
list1 = list(double_list[0])
list2 = list(double_list[1])
tmp = None
pHead1 = None
pHead2 = None
for i in range(len(list1)):
if tmp is None:
tmp = ListNode(list1[i])
pHead1 = tmp
else:
tmp.next = ListNode(list1[i])
tmp = tmp.next
tmp = None
for i in range(len(list2)):
if tmp is None:
tmp = ListNode(list2[i])
pHead2 = tmp
else:
tmp.next = ListNode(list2[i])
tmp = tmp.next
so = Solution()
merge_head = so.Merge(pHead1, pHead2)
p = merge_head
while p is not None:
print(p.val)
p = p.next
剑指offer 合并两个排序的链表 python2实现
最新推荐文章于 2021-07-27 21:18:33 发布