题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按非递减顺序排列
思路
很简单的头指针,尾指针,以及p,q指针分别指向l1,l2
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
p = list1
q = list2
temp1 =ListNode()
if(p==None and q==None):
return None
elif(p and q==None):
return p
elif(q and p == None):
return q
if(q.val>p.val):
first = p
p = p.next
else:
first =q
q= q.next
tail = first
while(q and p):
temp = ListNode
if(q.val>p.val):
temp=p
p=p.next
else:
temp=q
q=q.next
tail.next=temp
tail = temp
if(q):
tail.next=q
if(p):
tail.next=p
return first
标签:None,ListNode,21,val,next,链表,tail,热题
From: https://www.cnblogs.com/anamzingclown/p/17578515.html