Recursive? Why not using a dequeue? Short and clean solution gain


  • 0
    B

    Using recursive solution means an O(N) calling stack, which is essentially the same and less readable.\

    class Solution:
        # @param head, a ListNode
        # @return nothing
        def reorderList(self, head):
            queue = collections.deque()
            while head:
                queue.append(head)
                head = head.next
                
            dummy = ListNode(-1)
            head = dummy
            length = 0
            while queue:
                if length % 2 == 0:
                    head.next = queue.popleft()
                else:
                    head.next = queue.pop()
                head = head.next
                length += 1
            head.next = None

  • -1
    H

    Because the task is to use constant space (in-place).


  • 0
    T

    I don't think constant space is possible, unless this is a doubly linked list which it is not.
    Btw, I did it with deque, perfect and clean and accepted.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.