• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Easy: 21. 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

二、解题思路

   本题给定的两个链表是已经排好序的,首先定义一个空链表,然后从给定的两个链表的头节点开始比较,比较两个链接表的头节点,小的作为合并后链表的头结点,然后移动头指针,因为给定的两个链表都是已经排好序的,所以只需要比较两个链表的头部就行了。考虑到程序的鲁棒性,输入特殊的链表,比如空链表时,应该做出判断。                       
代码参考:http://blog.csdn.net/qq_28119401/article/details/52578096
def mergeTwoLists(l1,l2):
    if l1 is None:
        return l2
    if l2 is None:
        return l1
#定义虚表头
    dummyhead = ListNode(0)
    dummyhead.next = None
    p = dummyhead
    while l1 is not None and l2 is not None:
        if l1.val > l2.val:
            p.next = l2
            l2 = l2.next
        else:
            p.next = l1
            l1 = l1.next
        p = p.next
    if l1 is not None:
        p.next = l1
    else:
        p.next = l2
    return dummyhead.next

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-21 11:54  乐晓东随笔  阅读(131)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3