leecode-21. 合并两个有序链表

  • 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
1
2
3
4
示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:sarizzm time:2020/12/24 0024

# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1, l2):

if not l1:return l2
if not l2:return l1
p1 = l3 = ListNode()
while (l1 and l2):
if l1.val < l2.val:
p1.next = l1
l1 = l1.next
p1 = p1.next
else:
p1.next = l2
l2 = l2.next
p1 = p1.next
if l1 == None:
p1.next = l2
return l3.next
else:
p1.next = l1
return l3.next

def generateNode(nx):
node = ListNode()
p1 = node

for i in nx:
p1.next = ListNode(i)
p1 = p1.next
return node.next
n1 = [1,3,5,7,10]
n2 = [2,4,6,8,9]
node1 = generateNode(n1)
node2 = generateNode(n2)
# while(node1):
# print(node1.val)
# node1 = node1.next

node3 = Solution().mergeTwoLists(node1,node2)
while(node3):
print(node3.val)
node3 = node3.next

解法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2

#作者:LeetCode-Solution
#链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}

}
}

//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/