leetcode刷题记--> 21题解法(python解析)
题目定义
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接: leetcode_21题.
解题
本次使用3种方法
1. 暴力解决(列表)
计算出两个链表 把他们变成列表。进行排序,然后组成链表输出
2. 优化版,使用归并法
使用归并的思路将两个链表合并为一个链表
3. 递归解决
===================================================
实现
// An highlighted block
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2) :
'''
计算出两个链表 把他们变成列表。进行排序,然后组成链表输出
'''
l1_length = 0
l2_length = 0
l11 = l1
l1_list = []
l21 = l2
l2_list = []
while l11:
l1_length += 1
l1_list.append(l11.val)
l11 = l11.next
while l21:
l2_length += 1
l2_list.append(l21.val)
l21 = l21.next
# 找见最长的链表
l_list = l1_list + l2_list
l_list.sort()
res = ListNode(0)
exc = res
# 将相同的拼进去
for i in l_list:
node = ListNode(i)
exc.next = node
exc = exc.next
return res.next
def mergeTwoLists_1(self, l1, l2):
'''
类似于归并的思路
'''
if l1 is None or l2 is None:
return l1 if l1 else l2
l3 = ListNode(0)
res = l3
while l1 and l2:
if l1.val<l2.val:
l3.next = l1
l1 = l1.next
l3 = l3.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
if (l1 is None):
l3.next = l2
else:
l3.next = l1
return res.next
def mergeTwoLists_2(self, l1, l2):
'''
递归实现
'''
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists_2(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists_2(l1, l2.next)
return l2
def print_node(self,node):
'''
遍历链表
'''
while node:
print(node.val)
node = node.next
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(1)
e = ListNode(3)
f = ListNode(4)
a.next = b
b.next = c
d.next = e
e.next = f
s = Solution()
node = s.mergeTwoLists_2(a, d)
s.print_node(node)