Logic
Push
Enqueue the element.
If queue is not empty
Dequeue and enqueue all elements from front to rear-1.
Push 1
|_____|
top-->|__1__|
front
_____
1 | enqueue 1
____|
Push 2
|_____|
top-->|__2__|
|__1__|
front
___________
1 | 2 | enqueue 2
_____|_____|
front
________________
| 2 | 1 | dequeue and enqueue 1
_____|_____|____|
Push 3
top-->|__3__|
|__2__|
|__1__|
front
____________________
| 2 | 1 | 3 | enqueue 3
___|_____|____|____|
front
_________________________
| | 1 | 3 | 2 | dequeue and enqueue 2
____|____|____ |____|____|
front
______________________________
| | | 3 | 2 | 1 | dequeue and enqueue 1
____|____|____|_____|____|____|
void push(int element)
{
int i,j;
enqueue(element);
if(!empty())
{
j=s.q.rear;
for(i=s.q.front;i<j;i++)
{
dequeue(s.q.arr[i]);
enqueue(s.q.arr[i]);
}
}
}
Pop
Just dequeue the element at front.
|_____|
top-->|__2__|
|__1__|
front
______________________________
| | | 3 | 2 | 1 |
____|____|____|_____|____|____|
front
______________________________
| | | | 2 | 1 |
____|____|____|_____|_____|____|
void pop()
{
if(empty())
printf("\nStack is empty.Can't pop");
else
dequeue();
}
No comments:
Post a Comment