Friday, June 13, 2014

LeetCode (Python): Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

Solution:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return nothing
    def reorderList(self, head):
        if head == None:
            return head
        stack = []
        temp = head
        while temp != None:
            stack.append(temp)
            temp = temp.next
        list = head
        fromHead = head
        fromStack = True
        while (fromStack and list != stack[-1]) or ( not fromStack and list != fromHead):
            if fromStack:
                fromHead = fromHead.next
                list.next = stack.pop()
                fromStack = False
            else:
                list.next = fromHead
                fromStack = True
            list = list.next
        list.next = None

No comments :

Post a Comment