zoukankan      html  css  js  c++  java
  • LeetCode小白菜笔记[7]:Merge Two Sorted Lists

    LeetCode小白菜笔记[7]:Merge Two Sorted Lists

    21. Merge Two Sorted Lists [Easy]

    题目: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

    这道题的目的是将两个排好序的链表合并成一个并且还保持有序的性质。一个简单的想法就是在两个链表上各设置一个初始值在表头的可以移动的标签,两个游标所指向的元素比较大小,小的一个就加入Merged List,并把该游标后移一个。这样会移动到直到该游标所指的大于另一个所指的,然后另一个游标就变成了移动的,这样交替,就可以 Merge 两个有序链表了。

    代码如下:

    # 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
            """
            if l1 == None:
                return l2
            if l2 == None:
                return l1
            merged = ListNode(0)
            thisnode = ListNode(0)
            merged.next = thisnode
            thisnode1 = l1
            thisnode2 = l2
            while True :
                if (thisnode1.val < thisnode2.val): # compare the values
                    thisnode.next = thisnode1 # add smaller one to merge list
                    thisnode1 = thisnode1.next # shift the added tag by 1
                    thisnode = thisnode.next # merge list forward
                else :
                    thisnode.next = thisnode2
                    thisnode2 = thisnode2.next
                    thisnode = thisnode.next
                if (thisnode.next == None):
                    break
            if (thisnode1 == None):
                thisnode.next = thisnode2
            else:
                thisnode.next = thisnode1
            return merged.next.next

    结果如下:

    这里写图片描述

    总结:

    1. 开始时submission没有通过,由于没有考虑空链表的特殊情况。
    2. 对于while何时停止,开始时用两个链表其中一个到头就停止,发现结果错误,因为最末的数字根本没有参与计算和比较,于是考虑当merged链表的next指向None时停止,并且把剩下的没比较的直接接上(因为必然比merged当前的尾节点的数字要大,否则就应该在前面)。但是从上面的code可以看出 thisnode初始化的时候next就是None,因此应先进while再判断,应该用do~while语句,python中用 while True ~ if (condition) : break 代替。
    3. 对于涉及到指针的操作还不熟悉,需要加强。

    THE END

    2017/12/16 Sat 01:24 a.m.

  • 相关阅读:
    字符编码与函数
    linux打印彩色字
    企业级docker仓库Harbor部署
    PyPI使用国内源
    CentOS 7.2 升级内核支持 Docker overlay 网络模式
    购物车2
    购物车
    定制 cobbler TITLE 信息
    06.密码错误3次锁定
    05.for循环语句
  • 原文地址:https://www.cnblogs.com/morikokyuro/p/13256849.html
Copyright © 2011-2022 走看看