首页 > 编程语言 >Python合并两个有序链表

Python合并两个有序链表

时间:2024-08-16 17:48:28浏览次数:8  
标签:node __ Python self 链表 有序 root 节点

题目

合并两个有序链表,如l1=[1,3,4], l2=[1,2,4,5],合并后l3=[1,1,2,3,4,4,5]

解决思路

  1. 需要构建节点Node和链表LinkedList结构
  2. 如果root节点不确定,可以创建一个哑节点Node(0),作为root节点的前节点,也是初始节点(当前节点)
  3. 循环当l1当前节点不为None并且l2当前节点不为None时,那个节点值小,则当前节点.next=该节点,该节点后移一位
  4. 判断l1和l2当前那个有剩余(该链表当前节点不为None),则将当前节点.next=该节点

实现代码

节点Node及LinkedList类

class Node:
    def __init__(self, value, _next=None):
        self.value = value
        self.next = _next

    def __str__(self):
        return str(self.value)


class LinkedList:
    def __init__(self, root):
        self.root = root

    def __str__(self):
        values = []
        node = self.root
        while node is not None:
            values.append(node.value)
            node = node.next
        return str(values)

    @classmethod
    def from_list(cls, values):
        node = None
        for value in values[::-1]:
            node = Node(value, node)
        return cls(node)

这里的__str__和from_list方法只是为了方便使用及显示,可以移除

列表融合方法

def merge_linked_lists(list1, list2):
    # 创建一个哑节点作为合并后链表的头节点
    cur = pre_root = Node(0)
    list1_node, list2_node = list1.root, list2.root
    # 迭代比较两个链表的节点值,将较小的节点连接到合并后的链表中
    while list1_node is not None and list2_node is not None:
        if list1_node.value <= list2_node.value:
            cur.next = list1_node
            list1_node = list1_node.next
        else:
            cur.next = list2_node
            list2_node = list2_node.next
        cur = cur.next

    # 将剩余的节点连接到合并后的链表中
    if list1_node is not None:
        cur.next = list1_node

    if list2_node is not None:
        cur.next = list2_node

    return LinkedList(root=pre_root.next)


if __name__ == '__main__':
    l1 = LinkedList.from_list([1, 2,  4])
    l2 = LinkedList.from_list([1, 3,  4, 5])
    l3 = merge_linked_lists(l1, l2)
    print(l3)

标签:node,__,Python,self,链表,有序,root,节点
From: https://www.cnblogs.com/superhin/p/18363388/python_merge_sorted_linked_list

相关文章

  • 2024.8.15(python管理mysql、Mycat实现读写分离)
    一、python管理mysql1、搭建主mysql[root@mysql57~]#tar-xfmysql-5.7.44-linux-glibc2.12-x86_64.tar.gz [root@mysql57~]#cp-rmysql-5.7.44-linux-glibc2.12-x86_64/usr/local/mysql[root@mysql57~]#rm-rf/etc/my.cnf[root@mysql57~]#mkdir/usr/local/......
  • 随想录day3:203.移除链表元素|707.设计链表 |206.反转链表
    203.移除链表元素方法一:直接遍历,永远记得处理head,删除链表必须有前驱。/***Definitionforsingly-linkedlist.*publicclassListNode{*intval;*ListNodenext;*ListNode(){}*ListNode(intval){this.val=val;}*ListNode......
  • python管理MySQL数据库 mysql5.7读写分离 配置mycat(twenty-nine day)
    一、pymysql管理数据库1、搭建主mysql5.7[root@mysql57~]#lsanaconda-ks.cfg mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz[root@mysql57~]#tar-xfmysql-5.7.44-linux-glibc2.12-x86_64.tar.gz [root@mysql57~]#lsanaconda-ks.cfgmysql-5.7.44-linux-glibc2......
  • Python - Structural Design Patterns
    •TheadapterpatternTheadapterpatternisastructuraldesignpatternthathelpsusmaketwoincompatibleinterfaces compatible.Whatdoesthatreallymean?Ifwehaveanoldcomponentandwewanttouseitinanew system,oranewcomponentthatwew......
  • python的基础知识入门
    一.初聊Python为什么要学习Python?在学习Python之前,你不要担心自己没基础或“脑子笨”,我始终认为,只要你想学并为之努力,就能学好,就能用Python去做很多事情。在这个喧嚣的时代,很多技术或概念会不断兴起,我希望你能沉下心来去学习,不要急于求成,一步一个脚印。当你把某个技术学好、......
  • QT设置回调函数给python调用——参数法
    这种方法将回调函数作为python函数参数对象的方法来使用。Qt已经添加了Python库,并且能够正常调用Python的API,可以成功调用Python的代码块,这部分可以参考我另外一篇博客:1.QT相关函数定义1.1创建回调函数例如下面两个函数//实际的回调函数voidprintValue(intvalue){......
  • QT设置回调函数给python调用——内置模块法
    1.QT相关函数定义和 QT设置回调函数给python调用——参数法中的定义相同如下://实际的回调函数voidprintValue(intvalue){qDebug()<<"printValuevalue:"<<value;}intgetValue(intvalue){qDebug()<<"getValuevalue:"<<value;......
  • 【代码随想录】二、链表:2、设计链表
    部分图文参考于:代码随想录-707.设计链表。这道题目设计链表的五个接口:●获取链表第index个节点的数值●在链表的最前面插入一个节点●在链表的最后面插入一个节点●在链表第index个节点前面插入一个节点●删除链表的第index个节点可以说这五个接口,已经覆盖了链表的......
  • 【代码随想录】二、链表:1、移除链表元素
    部分图文参考于:代码随想录-203.移除链表元素。C++编程中记得要手动释放结点内存。链表操作中,可以使用原链表来直接进行删除操作,也可以设置一个虚拟头结点再进行删除操作。1.题目链接203.移除链表元素2.思路以链表1424来举例,移除元素4。如果使用C,C++编程语言的话,......
  • 【代码随想录】二、链表:理论基础
    原文链接:代码随想录-链表理论基础。1.什么是链表?链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。链表的入口节点称为链表的头结点也就是head。2.链表的类型2.1.......