-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path021_mergeTwoLists.py
More file actions
42 lines (39 loc) · 1.21 KB
/
021_mergeTwoLists.py
File metadata and controls
42 lines (39 loc) · 1.21 KB
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
root = new = ListNode(None)
if l1 == None:
return l2
if l2 == None:
return l1
while l1 and l2:
if l1.val == l2.val:
new.next = ListNode(l1.val)
new = new.next
new.next = ListNode(l2.val)
new = new.next
l1 = l1.next
l2 = l2.next
elif l1.val < l2.val:
new.next = ListNode(l1.val)
new = new.next
l1 = l1.next
elif l1.val > l2.val:
new.next = ListNode(l2.val)
new = new.next
l2 = l2.next
if l1!=None:
while l1:
new.next = ListNode(l1.val)
new = new.next
l1 = l1.next
if l2!=None:
while l2:
new.next = ListNode(l2.val)
new = new.next
l2 = l2.next
return root.next