How to implement a queue with three stacks?

前端 未结 5 1803
忘掉有多难
忘掉有多难 2020-12-12 08:51

I came across this question in an algorithms book (Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne).

Queue with three stacks. Implement

5条回答
  •  情歌与酒
    2020-12-12 09:16

    Note: This is meant to be a comment to the functional implementation of real-time ( constant time worst case ) queues with singly-linked-lists. I can't add comments due to reputation, but it'll be nice if someone could change this to a comment appended to the answer by antti.huima. Then again, it is somewhat long for a comment.

    @antti.huima: Linked lists are not the same as a stack.

    • s1 = (1 2 3 4) --- a linked list with 4 nodes, each pointing to the one on the right, and holding values 1, 2, 3 and 4

    • s2 = popped(s1) --- s2 is now (2 3 4)

    At this point, s2 is equivalent to popped(s1), which behaves like a stack. However, s1 is still available for reference!

    • s3 = popped(popped(s1)) --- s3 is (3 4)

    We can still peek into s1 to get 1, whereas in a proper stack implementation, element 1 is gone from s1!

    What does this mean?

    • s1 is the reference to the top of the stack
    • s2 is the reference to the second element of the stack
    • s3 is the reference to the third ...

    The additional linked-lists created now each serves as a reference/pointer! A finite number of stacks can't do that.

    From what I see in the papers/code, the algorithms all make use of this property of linked-lists to retain references.

    Edit: I'm referring only to the 2 and 3 linked-list algorithms make use of this property of linked-lists, as I read them first (they looked simpler). This is not meant to show that they are or are not applicable, just to explain that linked-lists aren't necessarily identical. I'll read the one with 6 when I'm free. @Welbog: Thanks for the correction.


    Laziness can also simulate pointer-functionality in similar ways.


    Using linked-list solves a different problem. This strategy can be used to implement real-time queues in Lisp (Or at least Lisps that insist on building everything from linked-lists): Refer to "Real Time Queue Operations in Pure Lisp" (linked to through antti.huima's links). It's also a nice way to design immutable lists with O(1) operation time and shared (immutable) structures.

提交回复
热议问题