将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
初始化两个链表头,一个用来记录两个有序链表比较结果,一个用来返回结果。
1.若两个链表不为空,则通过类似于列表指针方式比较,遍历链表,比较链表值,将较小值赋给新链表,并next。
2.若两个链表中有空,则将不为空的链表部分赋给新链表。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
newHead = ListNode(0)
cur = newHead
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
cur.next = l1 or l2
return newHead.next