0
点赞
收藏
分享

微信扫一扫

【LeetCode】88. 合并两个有序数组

1 ​​题目​​

2 思想

3 代码

# 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]:
if list1 is None and list2 is None:
return None
elif list1 is None:
return list2
elif list2 is None:
return list1

# step1.找出头结点
if list1.val <= list2.val:
head = list1
list1 = list1.next
else:
head = list2
list2 = list2.next
tail = head # 结果链表的尾节点

# print(head.val)
# 当两者都不是空的时候
while(list1 and list2):
if list1.val <= list2.val:
tail.next = list1
tail = list1
list1 = list1.next

else:
tail.next = list2
tail = list2
list2 = list2.next
if list1:
tail.next=list1
if list2:
tail.next =list2
return head


举报

相关推荐

0 条评论