题目
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
这就是思路就是建立一个中间变量来存储两个链表对应位置较小的数字;因为题目表示要返回一个链表,所以连起来的思路就是搭建一个伪链表头,然后一个移动节点指向它,然后通过遍历两个链表,把较小的数字存储在这个移动节点,最后返回表头
python:
# 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
"""
dum=cur=ListNode(0) #dum 是伪表头,cur是移动指针
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 #取出l2,并前进一步
cur.next=l1 if l1 else l2
return dum.next