Unit-4 - Stacks and Queues
Unit-4 - Stacks and Queues
*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
19
Pushing an element into stack
Algorithm to push an element into stack− Array
20
Pushing an element into stack
Algorithm to push an element into stack− Linked List
21
Pushing an element into stack
void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc
printf (“\n Stack (sizeof(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;
}
}
24
Popping an element from stack
25
Popping an element from stack
26
Popping an element from stack
•Indirect applications:
•Auxiliary data structure for algorithms
•Component of other data structures
Data Structures and Algorithms @Mahendra
Infix and Postfix Notations
•Infix: operators placed between operands:
A+B*C
•Postfix: operands appear before their operators:-
ABC*+
•There are no precedence rules to learn in postfix notation, and
parentheses are never needed
Operator Associativity
* / % left to right
+ - left to right
= += -= right to left
Operators on the top line have the highest precedence.
Precedence decreases line-by-line going down the table.
All operators on the same line have equal precedence.
34
Infix to Postfix
Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+
A + B * C 🡪 (A + (B * C)) 🡪 (A + (B C *) ) 🡪 A B C * +
36
Evaluation of postfix expression -
37
Evaluation of postfix expression -
38
Infix to postfix conversion
•Use a stack for processing operators (push and pop operations).
•Scan the sequence of operators and operands from left to right and
perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains operator of a lower
precedence and push the present operator.
39
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until
you see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the
stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association.
If the association is left to right, pop and print the top of the stack and then push the
incoming operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack,
pop the stack and print the top operator. Then test the incoming operator against the
new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)
40
Infix to Postfix Conversion
Requires operator precedence information
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.
41
Infix to Postfix Conversion
42
Infix to Postfix Conversion
43
Example - Conversion Infix to Postfix
44
Example - Conversion Infix to Postfix
45
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E
2 * * A
3 ( *( A
becomes
4 B *( AB
ABCD*+*E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
is also called as 9 ) * ABCD*+
Reverse Polish 10 + + ABCD*+*
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
Data Structures and Algorithms @Mahendra
Tower of Hanoi
*
Queue Representation
dequeue
create
QUEUE
isempty
size
• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Enqueue (ItemType newItem)
– Dequeue (ItemType& item)
Peek ()
a. This function helps to see the data at the front of the queue.
Algorithm of peek function − .
return queue[front]
end procedure
a. Implementation of peek function in C programming
language int peek()
{
return queue[front];
}
isfull()
As we are using single dimension array to implement queue,
we just check for the rear pointer to reach at MAXSIZE to
determine that queue is full.
In case we maintain queue in a circular linkedlist, the
algorithm will differ. Algorithm of isfull function −
*As queue maintains two data pointers, front and rear, its
operations are comparatively more difficult to implement
than stack.
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
Dequeue (ItemType& item)
*Function: Removes front item from queue and returns it in item.
*Preconditions: Queue has been initialized and is not empty.
*Postconditions: Front element has been removed from queue and
item is a copy of removed element.
Dequeue Operation
*Accessing data from queue is a process of two tasks − access the
data where front is pointing and remove the data after access.
The following steps are taken to perform dequeue operation −
ENQUEUE
front rear
DEQUEUE
front rear
struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;
front
front rearrear
front=0 1 2 3 4 5 6 7 8 rear = 9
▪ If rear != MAX – 1, then the rear will be incremented and value will
be inserted
90 49 7 18 14 36 45 21 99
front=0 1 2 3 4 5 6 7 rear= 8 9
front=1 2 3 4 5 6 7 8 rear= 9
Inserting an Element in a Circular Queue
9 10 7 18 14 36 45 21 99 72
rear=1 front=2 3 4 5 6 7 8
9
Algorithm to Insert an Element in a Circular Queue
0 1 2 3 4 5 6 7 8
9
▪ If the queue is not empty and after returning the value on front, if
front = rear, then it means now the queue has become empty and
so front and rear are set to -1.
Delete this element and set
81 rear = front = -1
0 1 2 3 4 5 6 7 8
front=rear= 9
▪ If the queue is not empty and after returning the value on front, if
front = MAX -1, then front is set to 0.
72 63 9 18 27 39 81
0 1 2 3 4 rear= 5 6 7 8
front= 9
Algorithm to Delete an Element from a Circular Queue
Step 1: IF FRONT = -1, then
Write “Underflow”
Goto Step 4
[END OF IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END OF IF]
[END OF IF]
Step 4: EXIT
4. Queue by Linked List
• Using a singly linked list to hold queue elements,
Using FRONT pointer pointing the start element,
Using REAR pointer pointing to the last element.
1 7 3 4 2 6 5 X
FRONT REAR
Inserting an Element in a Linked Queue
Algorithm to insert an element in a linked queue
29 37 45 54 63
0 1 2 LEFT = 3 4 5 6 RIGHT = 7 8
9
63 27 18
42
RIGHT = 0 1 2 3 4 5 6 LEFT = 7 8
9
6. Priority Queues
• A priority queue is a queue in which each element is assigned a
priority.
• The priority of elements is used to determine the order in which
these elements will be processed.
• The general rule of processing elements of a priority queue can be
given as:
o An element with higher priority is processed before an element
with lower priority
o Two elements with same priority are processed on a first come
first served (FCFS) basis
• Priority queues are widely used in operating systems to execute the
highest priority process first.
• In computer’s memory priority queues can be represented using
arrays or linked lists.
Linked List Representation of Priority Queues
A 1 B 2 C 3 D 3 E 4 X
The stack is based on LIFO(Last In First Out) The queue is based on FIFO(First In First Out)
principle principle.
Insertion Operation is called Push Operation Insertion Operation is called Enqueue Operation
Deletion Operation is called Pop Operation Deletion Operation is called Dequeue Operation
Push and Pop Operation takes place from one Enqueue and Dequeue Operation takes place
end of the stack from a different end of the queue
The most accessible element is called Top and The insertion end is called Rear End and the
the least accessible is called the Bottom of the deletion end is called the Front End.
stack
Simple Implementation Complex implementation in comparison to stack
Only one pointer is used for performing Two pointers are used to perform operations
operations
Difference between Stack & Queue
Stack Queue
Used to solve the recursive type problems Used to solve the problem having sequential
processing
Applications of Queues
•Direct applications:-
• Waiting lists
• Access to shared resources (e.g., printer)
• Multiprogramming
•Indirect applications:-
• Auxiliary data structure for algorithms
• Component of other data structures