题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路:
开辟一个新的链表,在原来两个链表上设置下标,将下标两个值进行比较,哪个小就把哪个链在新的链上,然后下标走一位,再进行比较。最后结果肯定是一个走完了一个没走完,将没走完的部分整体链上去就行了。
代码:
# 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
"""
curr1 = l1
curr2 = l2
curr3 = l3 = ListNode(0)
while curr1 and curr2:
if curr1.val <= curr2.val:
curr3.next = curr1
curr1 = curr1.next
curr3 = curr3.next
else:
curr3.next = curr2
curr2 = curr2.next
curr3 = curr3.next
if not curr1:
curr3.next = curr2
if not curr2:
curr3.next = curr1
return l3.next