Cisco Systems Interview Question
Software Engineer / DevelopersUse two stack to implement the queue.
Add function of queue:-
push item in stack1 but be sure that stack2 is empty.
if stack 2 is not empty then pop items from stack2 and push it in stack1
now add in stack1.
Delete function of queue:-
While deletion make sure that stack1 is empty.
If stack1 is not empty then pop items from stack1 and push it in stack2.
now pop item from stack2
void delete(int *x , stack_type *st_ptr1 , stack_type *st_ptr2)
{
int item;
while(!(stack_empty(st_ptr1)))
{
pop(&item,st_ptr1);
push(item,st_ptr2);
}
pop(x,st_ptr2);
}
void add(int x,stack_type *st_ptr1 , stack_type *st_ptr2)
{
int item;
while(!(stack_empty(st_ptr2)))
{
pop(&item,st_ptr2);
push(item,st_ptr1);
}
push(x,st_ptr1);
}
for complete c code
see "goursaha.freeoda.com/DataStructure/QueueUsing2Stack.html"
Use two stacks:
Stack1 = an LIFO stack that we will use to implement FIFO behavior
Stack2 = an LIFO stack to help us re-arrange the items in Stack1
Pushing an item X in Stack1:
1) If Stack1 is empty, push the item.
2) If Stack1 is not empty:
a) pop all items in Stack1 and push then in Stack2 one at a time
b) push the item X in Stack1
c) pop all items in Stack2 and push them in Stack1 one at a time
Popping an item in Stack1:
1) The items in the Stack1 are now arranged such that the first item pushed in Stack1 is now the first item to be popped.
- sk May 10, 2010