21. Merge Two Sorted Lists [easy] (Python)
2016-05-29 01:42
651 查看
题目链接
https://leetcode.com/problems/merge-two-sorted-lists/题目原文
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.题目翻译
将两个有序链表合并,返回新的链表。新链表应该是两个旧链表剪接得到的。思路方法
思路一
合并后的链表仍然是有序的,可以同时遍历两个链表,每次选取两个链表中较小值的节点,依次连接起来,就能得到最终的链表。代码
# 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 """ if not l1 or not l2: return l1 or l2 head = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return head.next
思路二
类似思路一,可以以头部节点较小的链表为基准,将另一个链表中的节点按大小插入到该链表中,形成一个大的有序链表代码
# 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 """ if not l1 or not l2: return l1 or l2 head = small = l1 if l1.val < l2.val else l2 big = l1 if l1.val >= l2.val else l2 pre = None while big: if not small: pre.next = big break if big.val >= small.val: pre = small small = small.next else: tmp = big.next pre.next = big pre = big big.next = small big = tmp return head
思路三
用递归的思想。代码
# 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 """ if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857843.html
相关文章推荐
- 程序自助发布
- 计算偏度Skewness与峰度kurtosis的python程序——简单
- Python2与Python3共存的环境配置
- 深入浅析python继承问题
- Python - 时间函数
- python 多线程之threading
- Python Queue模块
- idapython import site failed
- Python数据可视化之数据密度分布
- python初学(3)列表(List)应用(待续ing)
- 在Python标准库的json包中,提供了JSONEncoder和JSONDecoder两个类来实现Json字符串和dict类型数据的互相转换。
- LeetCode Largest Number
- 《Python3廖雪峰》datetime转timestamp练习题答案
- Python读取iOS安装包IPA中的信息和图片
- NumPy的详细教程
- python datetime 时间日期处理
- Python Decorator
- 第一次用python写线性回归
- python 使用记录
- Macpro + python + opencv