美文网首页
LeetCode#21 Merge Two Sorted Lis

LeetCode#21 Merge Two Sorted Lis

作者: 如烟花非花 | 来源:发表于2016-12-15 10:34 被阅读36次

    问题描述

    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.

    Subscribe to see which companies asked this question

    补充说明:

    把两个字符串合并成一个新的字符串,给定的两个字符串默认是有序的。

    方案分析

    1. 这个题目没什么好说的,典型的不能再典型的题目了。
    2. 其他的说明看注释吧。

    python实现

    # Definition for singly-linked list.
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            res_head = res_list = ListNode(None) # 申明一个新的串的头结点,同时申明一个指针指向这个节点。
            
            while(l1 and l2):
                if l1.val <= l2.val:
                    res_head.next = l1
                    l1 = l1.next
                else:
                    res_head.next = l2
                    l2 = l2.next
                res_head = res_head.next
    
            res_head.next = l1 if l1 else l2 # 这个地方既解决了两个字符串中一个为空的问题,因为有一个为空就不会执行上面的while语句;又解决了当一个字符串已经全部插入新串后,直接拼接剩下那个串到新串上面的操作。
            return res_list.next # 这里注意头结点不是我们要的那个节点
    

    相关文章

      网友评论

          本文标题:LeetCode#21 Merge Two Sorted Lis

          本文链接:https://www.haomeiwen.com/subject/kpgwmttx.html