leetcood学习笔记-21**-合并两个有序链表
2024-09-27 05:15:47
题目描述:
方法一:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(None)
node = res
while l1 and l2:
if l1.val<l2.val:
node.next,l1=l1,l1.next
else:
node.next,l2=l2,l2.next
node = node.next
if l1:
node.next=l1
else:
node.next=l2
return res.next
方法二:递归
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None and l2 is None:
return None
if l1 is None:
return l2
if l2 is None:
return l1 if l1.val > l2.val:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2 l1.next = self.mergeTwoLists(l1.next, l2)
return l1
python 数据结构之单链表的实现
链接:https://www.cnblogs.com/yupeng/p/3413763.html
最新文章
- [LeetCode] Design Hit Counter 设计点击计数器
- [js开源组件开发]localStorage-cache本地存储的缓存管理
- mysql 将时间戳直接转换成日期时间
- POJ 1113 Wall(Graham求凸包周长)
- HTML5 History对象,Javascript修改地址栏而不刷新页面
- Docker 组件如何协作?- 每天5分钟玩转容器技术(8)
- Java:参数数量可变的方法
- MysqL自动提交机制的关闭
- eclipse 导入gradle引入多模块项目,引入eclipse后变成了好几个工程
- Simditor 富文本编辑器多选图片上传、视频连接插入
- “多个单核CPU”与“单个多核CPU”哪种方式性能较强?
- 爬虫3 requests基础2 代理 证书 重定向 响应时间
- index-document-shard
- Python使用matplotlib模块绘制多条折线图、散点图
- LoadRunner中的IP欺骗的设置以及误区
- [PA2014]Pakowanie
- Reverting back to the R12.1.1 and R12.1.3 Homepage Layout
- oracle过程书写规范
- Android中Activity的四种启动方式
- http协议详解(2)