forked from das-jishu/algoexpert-data-structures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinverted-bisection.py
48 lines (39 loc) · 922 Bytes
/
inverted-bisection.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
# INVERTED BISECTION
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def invertedBisection(head):
# Write your code here.
if head is None or head.next is None:
return head
prev = None
slow = head
fast = head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
hasEvenCount = True if fast == None else False
prev.next = None
if hasEvenCount:
firstHalf = reverseLinkedList(head)
secondHalf = reverseLinkedList(slow)
head.next = secondHalf
return firstHalf
else:
firstHalf = reverseLinkedList(head)
secondHalf = reverseLinkedList(slow.next)
head.next = slow
slow.next = secondHalf
return firstHalf
def reverseLinkedList(head):
prev = None
cur = head
while cur is not None:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev