将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret_l=[]
if l1 is None or l2 is None:
if l1 is None :
return l2
else:
return l1
else:
while 1:
if l1.next and l2.next:
ret_l.append(l1.val)
ret_l.append(l2.val)
l1=l1.next
l2=l2.next
elif l1.next:
ret_l.append(l1.val)
l1=l1.next
elif l2.next:
ret_l.append(l2.val)
l2=l2.next
else:
if l1.next==None:
ret_l.append(l1.val)
if l2.next==None:
ret_l.append(l2.val)
break
ret_l.sort()
ret_node=""
for i in range(0,len(ret_l)):
if i ==0:
ret_node=ListNode(ret_l[0])
cur_node=ret_node
else:
new_node=ListNode(ret_l[i])
cur_node.next=new_node
cur_node=cur_node.next
return ret_node