-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Two Sorted Lists
More file actions
60 lines (58 loc) · 1.83 KB
/
Merge Two Sorted Lists
File metadata and controls
60 lines (58 loc) · 1.83 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 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
"""
head = ListNode(None)
cur = ListNode(None)
i = l1
j = l2
while(1):
if head.val == None:
if i != None and j != None:
if i.val > j.val:
head.val = j.val
j = j.next
cur = head
else:
head.val = i.val
i = i.next
cur = head
elif i == None and j != None:
head = j
return head
elif i != None and j == None:
head = i
return head
else:
head = None
return head
else:
temp = ListNode(None)
if i != None and j != None:
if i.val > j.val:
temp.val = j.val
j = j.next
cur.next = temp
cur = temp
else:
temp.val = i.val
i = i.next
cur.next = temp
cur = temp
elif i == None and j != None:
cur.next = j
return head
elif i != None and j == None:
cur.next = i
return head
else:
cur = None
return head