题目描述:
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
解答
方法1:不创建新的链表,取一个链表插入另一个链表中
# 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 and not l2:
return None
if not l1:
return l2
if not l2:
return l1
while l2:
node_temp = ListNode(l2.val) #取出链表l2的一个值,再调用函数插入到l2中
l1 = insert_list(l1, node_temp)
l2 = l2.next
return l1
def insert_list(l1, node1): #可能是头部、中部、尾部插入
if node1.val < l1.val:
node1.next = l1
l1 = node1
return l1 #头部插入
curnode = l1
nextnode = l1.next
while nextnode:
if node1.val < nextnode.val:
node1.next = curnode.next
curnode.next = node1
return l1 #中部插入
else:
curnode = nextnode
nextnode = nextnode.next
curnode.next = node1
return l1 #尾部插入
方法2:新建一个链表,取两条链表中的最小元素依次插入, 又名迭代
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 and not l2:
return None
if not l1:
return l2
if not l2:
return l1
l3 = ListNode(0) #使用有头节点的链表
curnode = l3
while l1 and l2:
if l1.val < l2.val:
curnode.next = l1
l1 = l1.next
else:
curnode.next = l2
l2 = l2.next
curnode = curnode.next
if l1:
curnode.next = l1
elif l2:
curnode.next = l2
return l3.next
方法3:递归
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 and not l2:
return None
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
pre = l1
pre.next = self.mergeTwoLists(l1.next, l2)
else:
pre = l2
pre.next = self.mergeTwoLists(l1, l2.next)
return pre
不知道为何,使用递归方法在leetcode编译总是失败,之后再琢磨一下!