13 Stacks and Queues
13 Stacks and Queues
Debasis Samanta
Computer Science & Engineering
Indian Institute of Technology Kharagpur
Spring-2017
Lecture #13
Stack & Queue
*Stack *Queue
* Basic principles * Basic principles
* Operation of stack * Operation of queue
* Stack using Array * Queue using Array
* Stack using Linked List * Queue using Linked List
* Applications of stack * Applications of queue
pop
create
STACK
isempty
isfull
PUSH
top
top
POP
top
top
PUSH OPERATION
top
POP OPERATION
top
void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}
• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures
A+B* C (A + (B * C)) (A + (B C *) ) A B C * +
Operands:
Add to postfix expression.
Close parenthesis:
pop stack symbols until an open parenthesis appears.
Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push
the operator.
End of input:
Pop all remaining stack symbols and add to the expression.
ABC D * +* E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
9 ) * ABCD*+
is also called as
10 + + ABCD*+*
Reverse Polish
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
Autumn 2016 30
Queue
dequeue
create
QUEUE
isempty
size
ENQUEUE
front rear
DEQUEUE
front rear
struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;
front
front rearrear
• Indirect applications:-
• Auxiliary data structure for algorithms
• Component of other data structures