本题是比较基础的链表题。链表题的典型套路。
1.思路
解题步骤
1)创建头节点,并用res记录其位置
2)都不为None时,比较并且插入,注意每次插入后的l1orl2以及head的后移
3)当有出现None时,插入另一个的剩余部分
4)返回res.next
2.代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
res = head
while l1 != None and l2 != None:
if l1.val > l2.val:
head.next = l2
l2 = l2.next
else:
head.next = l1
l1 = l1.next
head = head.next
if l1 == None:
head.next = l2
elif l2 == None:
head.next = l1
return res.next