LeetCode-21 有序链表的合并

问题描述:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
 9         curr = head = ListNode(0)  #curr表示工作指针,head表示链表的头
10         while l1 and l2:            #如果两者都不为空
11             if l1.val<l2.val:
12                 curr.next = l1
13                 l1 = l1.next
14             else:
15                 curr.next = l2
16                 l2 = l2.next
17             curr = curr.next            #每一次的while循环都要让curr向后移动一位
18         curr.next = l1 or l2            #最后将非空的剩余链表链接到后面
19 
20         return head.next    

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2020-02-22 16:43  Halo辉Go  阅读(173)  评论(0编辑  收藏  举报