Chap 02 - Stacks and Queues (Autosaved)
Chap 02 - Stacks and Queues (Autosaved)
1
Unit 2
Stacks and Queues:
Syllabus:
Introduction, Stack and queue as ADT,
representation and Implementation of stack and
queue using sequential and linked allocation,
Circular queue and its implementation,
Application of stack for expression evaluation
and conversion, recursion and priority queue.
2
Assignment questions:
1. Consider the stack, where stack is allocated N=6 memory cells,
Suppose initially stack contains, A, D,E,F,G(top of the stack).
Then the following operations are called in order. Show the stack
top and any other situation raised while doing each of the
operation. i) push(stack, k) ii) pop( stack, item) iii)
push(stack, L) iv) Push( stack, S) v) pop(stack, item)
2. Write the prefix form of the infix expression (a-b)/c.
3. convert the expression ((A+B)* C-(D-E)^(F+G)) to equivalent
prefix and postfix notations.
4. Write and explain insert() and delete() used in queue.
5. What is priority queue? Give two example of system in which
priority queue is used.
6. Write and explain iterative procedure to calculate factorial of n.
Stack
4
Basic Principal
•A stack is an Abstract Data Type (ADT), commonly used in most
programming languages. It is named stack as it behaves like a real-world
stack, for example – a deck of cards or a pile of plates, etc.
o pop
• Insertion in a stack is done using push function and removal from a stack is
Stack allows access to only the last element inserted hence, an item can be
inserted or removed from the stack from one end called the top of the stack. It is
o capacity stands for the maximum number of elements stack can hold.
Prof. K. 7
Stack
Conditions
-1
Prof. K. 8
Stack as an ADT
Set of values for STACK
Stack S is a finite collection of elements having same data type and all
operation are carried out at one end called top.
push
pop
create STACK
isempty
isfull 9
PUSH
Operation
⚫The process of adding one element or item to
the stack is represented by an operation called
as the PUSH operation.
10
PUSH
Operation:
⚫ The process of adding one element or item to the stack is
represented by an operation called as the PUSH operation.
⚫ The new element is added at the topmost position of the stack.
ALGORITHM:
PUSH (STACK, TOP, SIZE, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of
the element of the array. ITEM to be inserted.
Step 1: if TOP = N then [Check Overflow]
PRINT “ STACK is Full or Overflow”
Exit
[End if]
Step 2: TOP = TOP + 1 [Increment the TOP]
Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
11
POP
Operation
The process of deleting one element or item from
the stack is represented by an operation called
as the POP operation.
When elements are removed continuously from a
stack, it shrinks at same end i.e., top
12
POP
Operation
The process of deleting one element or item from the
stack is represented by an operation called as the POP
operation.
ALGORITHM: POP (STACK, TOP, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of
the element of the array. ITEM to be inserted.
Step 1: if TOP = 0 then [Check Underflow]
PRINT “ STACK is Empty or
Underflow”
Exit
[End if]
Step 2: ITEM = STACK[TOP] [copy the TOP
Step 3: TOP = TOP - 1 Element] [Decrement
Step 4: Return the TOP]
13
PEEK
Operation
The process of returning the top item from the
stack but does not remove it called as the POP
operation.
15
Push using Stack PUSH
top
top
16
POP
Pop using Stack
top
top
17
18
19
20
Arithmetic Expression
⚫ An expression is a combination of operands and
operators that after evaluation results in a single value.
· Operand consists of constants and variables.
· Operators consists of {, +, -, *, /, ), ] etc.
⚫ Expression can be
Infix Expression: If an operator is in between two operands, it is called
infix expression.
⚫ Example: a + b, where a and b are operands and + is an operator.
Postfix Expression: If an operator follows the two operands, it is called
postfix expression.
⚫ Example: ab +
Prefix Expression: an operator precedes the two operands, it is called
prefix expression.
21
22
23
24
25
Infix to Postfix Rules
Current Operator Postfix string
symbol Stack
Expression: 1 A A
2 * * A
A * (B + C * D) + E
3 ( *( A
becomes 4 B *( AB
5 + *(+ AB
ABC D * +* E+ 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+
27
28
29
Application of Stacks
⚫It is used to reverse a word. You push a given word to
stack – letter by letter and then pop letter from the stack.
⚫“Undo” mechanism in text editor.
⚫Backtracking: This is a process when you need to
access the most recent data element in a series of
elements. Once you reach a dead end, you must
backtrack.
⚫Language Processing: Compiler’ syntax check for
matching braces in implemented by using stack.
⚫Conversion of infix expression into prefix and postfix.
⚫Recursion uses stack
30
Implementation of stack
using linked list.
• we can also use linked list to implement stack. Linked list
allocates the memory dynamically.
• In linked list implementation of stack, the nodes are
maintained non-contiguously in the memory. Each node
contains a pointer to its immediate successor node in the stack.
Push operation:
Adding a node to the stack is referred to as push operation. Pushing an
element to a stack in linked list implementation is different from that of an
array implementation. In order to push an element onto the stack, the
following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of
the list. This includes assigning value to the data part of the node
and assign null to the address part of the node.
3. If there are some nodes in the list already, then we have to add the
new element in the beginning of the list (to not violate the property
of the stack). For this purpose, assign the address of the starting
element to the address field of the new node and make the new
node, the starting node of the list.
Stack using Linked list :
Deleting a node from the
stack (POP operation)
we need to follow the following steps :
1. Check for the underflow condition: The underflow
condition occurs when we try to pop from an already
empty stack. The stack will be empty if the head
pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the
elements are popped only from one end, therefore, the
value stored in the head pointer must be deleted and
the node must be freed. The next node of the head
node now becomes the head node.
Queue
35
Basic Idea
•Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue).
36
Queue
⚫A queue is an ordered collection of items where an
item is inserted at one end called the “rear” and an
existing item is removed at the other end, called
the “front”.
⚫Queue is also called as FIFO list i.e. First-In First-
Out.
⚫In the queue only two operations are allowed enqueue
and dequeue.
⚫Enqueue means to insert an item into back of
the queue.
⚫Dequeue means removing the front item. The people
standing in a railway reservation row are an
example of queue.
Types of
Queues
⚫Queue can be of four
types:
o Simple Queue
o Circular Queue
o Priority Queue
38
Simple
⚫Queue
Simple Queue: In simple queue insertion
occurs at the rear end of the list and
deletion occurs at the front end of the list.
39
Circular
⚫Queue
Circular Queue: A circular queue is a queue
in which all nodes are treated as circular
such that the last node follows the first node.
40
Priority
Queue
⚫A priority queue is a queue that contains
items that have some present priority. An
element can be inserted or removed from
any position depending upon some
priority.
41
Operation on
Queues
⚫Queue( ): It creates a new queue that
is empty.
⚫enqueue(item): It adds a new item to the
rear of the queue.
⚫dequeue( ): It removes the front item
from the queue.
⚫isEmpty( ): It tests to see whether the
queue is empty.
⚫size( ): It returns the number of items in
the queue.
42
Working of Queue
Queue operations work as follows:
Front=0
Rear=-1 Enqueue(10)
10
Front=0
Front will be incremented
Rear=0 for adding only first
element in queue
Enqueue(20) Enqueue(30)
10 20 30
Rear=0
Queue Full Condition
When Rear=SIZE-1 Queue is Full
10 20 30 40 50
Front=0 Rear=4
Dequeue Operation on Queue
On each dequeue front value is incremented by 1
Dequeue() Dequeue()
10 20 30 40 50
space.
Circular Queue
first element.
the queue)
by REAR
2. Dequeue Operation
underflow
zero
Applications of Queue:
There are several applications of queues in computer science.
occur.
57
Queue using Linked List
58
Basic Idea
•Basic idea:
• Create a linked list to which items would be added to one end
and deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted).
Rear
ENQUEUE
front rear
Queue: Linked List Structure
DEQUEUE
front rear
61
Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};
struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;
62
Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q)
prev->next=NULL;
{
free(q1);
queue *q1;
return (val);
q1=q;
}
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}
Problem With Array Implementation
•The size of the queue depends on the number and order of enqueue and
dequeue.
•It may be situation where memory is available but enqueue is not possible.
ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N
front
front rearrear