You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现无需排序的两个链表合并功能?

实现思路
  • 不需要排序逻辑,仅需将被合并链表的头节点直接挂载到当前链表的尾节点后即可
  • 全程直接复用原节点的引用,不做节点拷贝,自然满足修改原链表节点、合并后链表同步更新的要求
具体代码修改

直接在原LinkedList类中新增merge方法即可:

def merge(self, other):
    # 被合并链表为空,无需操作
    if other.head is None:
        return
    # 当前链表为空,直接指向被合并链表头
    if self.head is None:
        self.head = other.head
        return
    # 遍历找到当前链表的尾节点
    current = self.head
    while current.next is not None:
        current = current.next
    # 尾节点的next指向被合并链表的头
    current.next = other.head

如果你的原类缺少append和print_list辅助方法,可以补上方便测试:

def append(self, data):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
        return
    current = self.head
    while current.next:
        current = current.next
    current.next = new_node

def print_list(self):
    current = self.head
    res = []
    while current:
        res.append(str(current.data))
        current = current.next
    print(f"[{','.join(res)}]")
测试验证

用你给出的场景验证效果:

ls = LinkedList()
for num in [2,3,4,5]:
    ls.append(num)
ls2 = LinkedList()
for num in [42,17]:
    ls2.append(num)

ls.merge(ls2)
ls.print_list() # 输出 [2,3,4,5,42,17]

ls2.head.data = 24
ls2.print_list() # 输出 [24,17]
ls.print_list() # 输出 [2,3,4,5,24,17]

内容的提问来源于stack exchange,提问作者user17280635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:45:02