Skip to content

Commit febdb15

Browse files
Add files via upload
1 parent 4da2f81 commit febdb15

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# 基本思路就是将一个链表不断插入到另外一个链表中
2+
# 44ms 99.41%
3+
4+
# Definition for singly-linked list.
5+
# class ListNode:
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.next = None
9+
10+
class Solution:
11+
def mergeTwoLists(self, l1, l2):
12+
"""
13+
:type l1: ListNode
14+
:type l2: ListNode
15+
:rtype: ListNode
16+
"""
17+
if not l1:
18+
return l2
19+
if not l2:
20+
return l1
21+
22+
main, sub = (l2, l1) if l1.val > l2.val else (l1, l2)
23+
24+
main_mid = main
25+
sub_mid = sub
26+
27+
while main_mid.next is not None:
28+
if main_mid.next.val >= sub_mid.val:
29+
30+
temp_node = sub_mid
31+
sub_mid = sub_mid.next
32+
33+
next_node = main_mid.next
34+
main_mid.next = temp_node
35+
temp_node.next = next_node
36+
37+
main_mid = temp_node
38+
39+
if sub_mid is None:
40+
return main
41+
else:
42+
main_mid = main_mid.next
43+
main_mid.next = sub_mid
44+
return main

0 commit comments

Comments
 (0)