1.要求
合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
2.思路及代码
1.思路 ,创建一个新列表xin,同时遍历两个链表l1,l2,比较大小,小的加到新的列表中去,然后知道其中一个遍历完,最后再把余下的加到新的列表后面就可以了。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
xin=ListNode(0)
cur=xin
while l1 and l2:
if l1.val < l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
if l1:
cur.next=l1
if l2:
cur.next=l2
return xin.next
2.思路 ,和思路1相同但是用了递归的思想。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None:
return l2
if l2 == None:
return l1
res = ListNode(0)
if l1.val <= l2.val:
res = l1
res.next = self.mergeTwoLists(l1.next,l2)
else:
res = l2
res.next = self.mergeTwoLists(l1,l2.next)
return res
3.问题
在编写代码时一定要记得每次循环把新的链表向下移动一位。