Thursday, September 15, 2011

implement a deque using stacks

This  is a kind of "two snakes" game

1234

snake1      snake2

1 push

2 push
1

3 push
2
1

               3 push
     
               2 push
               3

               1 push       -> ready to pop
               2
               3


so push in 2nd stack if empty.

1 comment:

  1. Have 2 stacks(say stack1 and stack2). Push into one stack (say stack1)

    To perform pop operation, check if stack2 contains any element,if yes then pop stack2. else transfer n-1 elements from stack1 to stack2 and return nth element.

    ReplyDelete