Building a queue with two stacks

Mar 31, 2011 12:11

Here's a data-structure I use almost every day. It's an implementation¹ of a queue. You have two stacks, an in-stack and an out-stack. To add a new item, push it onto the in-stack. To remove an item, take the top item off the out-stack; if the out-stack's empty, push all the items on the in-stack onto the out-stack in reverse order and then take ( Read more... )

computers, programming, c++, beware the geek, clothes, clothing

Leave a comment

Comments 17

stronae March 31 2011, 12:21:43 UTC
I love the application to laundry, and I also love the kitties. Kitties!

Reply

pozorvlak March 31 2011, 12:33:50 UTC
They're gorgeous, aren't they? We've had them for just over two months now (since Burns Night, which is part of the reason we called him Haggis).

Reply


fanf March 31 2011, 15:52:50 UTC
This is the standard implementation of a queue in functional programming languages :-)

Are your t-shirts immutable?

Reply

pozorvlak March 31 2011, 16:21:29 UTC
They're very rarely modified, unless you count getting them dirty.

Reply

fanf March 31 2011, 16:27:43 UTC
That's just a garbage collection problem, isn't it? At least, for very small garbage objects.

Reply

pozorvlak March 31 2011, 17:02:28 UTC
:-)

Reply


kragen March 31 2011, 18:24:03 UTC
Very nice ( ... )

Reply


anonymous March 31 2011, 21:05:28 UTC
This was in the first or so homework of the first data structures compsci class I took back in the day.

Reply


anonymous April 1 2011, 10:26:04 UTC
When the out-stack is empty, why not just swap the stack references? The out-stack becomes the new in-stack, and the old-instack becomes the new out-stack. Then, proceed as usual. (Resembles stop n' copy GC algorithm :)

Reply

pozorvlak April 1 2011, 11:02:23 UTC
Because then the in-stack would be upside-down :-)

Reply

anonymous April 1 2011, 11:55:53 UTC
Oops. I couldn't take wearing my Sunday t-shirt on a Thursday ...

Reply

pozorvlak April 1 2011, 15:55:35 UTC
I'm not so worried about that; I guess your system does have the desired property that all T-shirts are worn approximately as often as each other.

Reply


Leave a comment

Up