前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q21 Merge Two Sorted Lists

Q21 Merge Two Sorted Lists

作者头像
echobingo
发布2018-04-25 16:37:29
5230
发布2018-04-25 16:37:29
举报

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:
代码语言:javascript
复制
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解题思路:

创建一个新链表,包括头结点和工作结点。在比较的过程中为工作结点的后续创建新的结点,直至有一个链表为空。最后,把另一个链表全部加入到工作结点的后续。

注意点:

Pyhon链表中,一个链表不可以赋值给一个结点,如 cur = l2、cur = l2.next (l2为链表),但是可以把链表赋值给一个结点的地址,如 cur.next = l2、cur.next = l2.next (l2为链表)

Python实现:
代码语言:javascript
复制
# 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
        """
        head = ListNode(-1)  # 返回头结点
        cur = head # 当前结点
        while l1 != None and l2 != None:
            if l1.val <= l2.val:
                cur.next = ListNode(l1.val) # 为cur的后续创建一个结点
                l1 = l1.next
            else:
                cur.next = ListNode(l2.val)
                l2 = l2.next
            cur = cur.next  # 当前结点后移
        if l1 == None:  # 如果一个链全部遍历完,则将另外一个链接到后面
            cur.next = l2
        if l2 == None:
            cur.next = l1
        return head.next   # 返回合并好的新链表        
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example:
  • 解题思路:
  • 注意点:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档