|
| 1 | +# Reorder List |
| 2 | +# https://leetcode.com/problems/reorder-list/ |
| 3 | + |
| 4 | +# Definition for singly-linked list. |
| 5 | +# class ListNode(object): |
| 6 | +# def __init__(self, val=0, next=None): |
| 7 | +# self.val = val |
| 8 | +# self.next = next |
| 9 | +class Solution(object): |
| 10 | + def detachInMiddle(self, head): |
| 11 | + rabbit = head |
| 12 | + tortoise = head |
| 13 | + # move rabbit 1X times and rabbit 2X times. This will make sure tortoise is in the middle of list by the time rabbit reaches the end of the list. |
| 14 | + while(rabbit): |
| 15 | + rabbit = rabbit.next |
| 16 | + if (rabbit and rabbit.next): |
| 17 | + rabbit = rabbit.next |
| 18 | + tortoise = tortoise.next |
| 19 | + # now toroise is in the middle |
| 20 | + newHead = tortoise.next |
| 21 | + # detach the lists |
| 22 | + tortoise.next = None |
| 23 | + return head, newHead |
| 24 | + |
| 25 | + # Detach the nodes of the list and put it in stack. |
| 26 | + def putListInStack(self, root): |
| 27 | + stack = [] |
| 28 | + while(root): |
| 29 | + # add node to stack |
| 30 | + stack.append(root) |
| 31 | + # assign current node to previous node |
| 32 | + prevNode = root |
| 33 | + # move the current node to next position |
| 34 | + root = root.next |
| 35 | + # detach the previous node from the list |
| 36 | + prevNode.next = None |
| 37 | + return stack |
| 38 | + |
| 39 | + def attachStackNodesToList(self, l1, stack): |
| 40 | + # assign pointer to head of list 1 |
| 41 | + ptr = l1 |
| 42 | + while(stack): |
| 43 | + # pop the top of stack |
| 44 | + top = stack.pop() |
| 45 | + # assign previous and next nodes |
| 46 | + prevNode = ptr |
| 47 | + nextNode = ptr.next |
| 48 | + # concatinate top node in between previous and next nodes. |
| 49 | + prevNode.next = top |
| 50 | + top.next = nextNode |
| 51 | + # advance the ptr |
| 52 | + ptr = nextNode |
| 53 | + |
| 54 | + def reorderList(self, head): |
| 55 | + # detach the list in middle. |
| 56 | + l1, l2 = self.detachInMiddle(head) |
| 57 | + # put l2 in stack, this helps in reversing the list |
| 58 | + stack = self.putListInStack(l2) |
| 59 | + # attach stack nodes to the list 1 |
| 60 | + self.attachStackNodesToList(l1, stack) |
| 61 | + return l1 |
| 62 | + """ |
| 63 | + :type head: ListNode |
| 64 | + :rtype: None Do not return anything, modify head in-place instead. |
| 65 | + """ |
| 66 | + |
0 commit comments