1、问题描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
来源:力扣
链接:合并两个有序链表
2、解题思路
将两个链表的所有数据放到一个列表中,排序,根据这个列表返回一个新的链表。
3、python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def linkListFromList(self,c:list)->ListNode:
if not c:
return None
head=ListNode(c[0])
current=head
for i in c[1:]:
tmp=ListNode(val=i)
current.next=tmp
current=tmp
return head
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res=[]
while l1:
res.append(l1.val)
l1=l1.next
while l2:
res.append(l2.val)
l2=l2.next
res.sort()
return self.linkListFromList(res)
4、结果
从结果中看出执行还是比较快的。力扣网站中的很多题解答案是根据递归的思路来解决的,有兴趣的朋友可以去看一下。