Skip to content

Commit 72d2278

Browse files
authored
Create merge-in-between-linked-lists.py
1 parent 2a5e936 commit 72d2278

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(m + n)
2+
# Space: O(1)
3+
4+
# Definition for singly-linked list.
5+
class ListNode(object):
6+
def __init__(self, val=0, next=None):
7+
pass
8+
9+
10+
class Solution(object):
11+
def mergeInBetween(self, list1, a, b, list2):
12+
"""
13+
:type list1: ListNode
14+
:type a: int
15+
:type b: int
16+
:type list2: ListNode
17+
:rtype: ListNode
18+
"""
19+
prev_first, last = None, list1
20+
for i in xrange(b):
21+
if i == a-1:
22+
prev_first = last
23+
last = last.next
24+
prev_first.next = list2
25+
while list2.next:
26+
list2 = list2.next
27+
list2.next = last.next
28+
last.next = None
29+
return list1

0 commit comments

Comments
 (0)