合并两个排序的链表python(剑指offer 25)
2021/12/14 22:46:37
本文主要是介绍合并两个排序的链表python(剑指offer 25),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# 剑指 Offer 25. 合并两个排序的链表
示例1:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
# 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 """ # 关键条件递增 # 通过指针对比反复对比链接 dummy_head = ListNode(0) cur = dummy_head cur1, cur2 = l1, l2 while cur1 and cur2: if cur1.val >= cur2.val: cur.next = cur2 cur2 = cur2.next else: cur.next = cur1 cur1 = cur1.next cur = cur.next # 前面操作只是找到cur的next,还需要cur进行移动 cur.next = cur1 if cur1 else cur2 #连接剩下的链表 return dummy_head.next
这篇关于合并两个排序的链表python(剑指offer 25)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础