这道题也是很经典的一道题了,408的算法题中也考过这个思想,因为两个链表已是升序,合并只需要两个指针,分别指向两个表的表头,分别比较两个指针所指向的结点的val,小的就插入到目标链表里面,再后移相应指针,直到有一个链表为空,再把剩下的非空链表全部查到目标链表后面即可
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
ans = ListNode()
current = ans
i = list1
j = list2
while i is not None and j is not None:
if i.val <= j.val:
current.next = ListNode(i.val)
i = i.next
else:
current.next = ListNode(j.val)
j = j.next
current = current.next
current.next = i if i is not None else j
return ans.next