-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinterviewbit-linked-lists-k-reverse-linked-list.py
51 lines (44 loc) · 1.37 KB
/
interviewbit-linked-lists-k-reverse-linked-list.py
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
# Alas, I kept screwing up my more elegant solution :-(
def reverse_bucket(self, head):
current = head
temp = None
while True:
next = current.next
temp, current.next = current, temp
if next:
current = next
else:
return current
def reverseList(self, A, B):
if not A or not A.next or B == 1:
return A
buckets = []
bucket_head = A
current = A
count = 0
while current:
count += 1
if count % B == 0:
old_bucket_head = bucket_head
bucket_head = current.next
current.next = None
current = bucket_head
buckets.append(self.reverse_bucket(old_bucket_head))
else:
current = current.next
new_head = buckets[0]
for i, bucket in enumerate(buckets[:-1]):
current = bucket
while current.next:
current = current.next
current.next = buckets[i + 1]
return new_head