【每日一题leetcode】Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new
list should be made by splicing together the nodes of the first two
lists.

Example:

Input: 1->2->4, 1->3->4
Output: 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
        """
        #因为是链式列表,我们添加完node后,指针在列表末尾。所以为了返回整个列表,
        #这里增加变量copy
        copy = new_l = ListNode(0) 
        while l1 and l2:
            if l1.val < l2.val:   
                new_l.next = l1                
                l1 = l1.next   #这里只有l1的指针后移了一位,再次执行时是l1的第二个与l2的第一个做比较
                            
            else:
                new_l.next = l2
                l2 = l2.next
                
            new_l = new_l.next              
            
        new_l.next = l1 or l2
        
        return copy.next


第一次做的时候少了new_l = new_l.next 这句,返回的结果是列表的最后一个值。

如果没有这句,指针对一直停在当前位置,值不断被覆盖。

还可以在最开始添加判断语句,是否两个列表有一个为空。

if not l1 or not l2:
   return l2 or l1

猜你喜欢

转载自blog.csdn.net/github_39395521/article/details/80801677
今日推荐