您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: