SlideShare a Scribd company logo
DATA STRUCTURES USING
C++
Stacks and
queues
Ekta Vaswani
Assistant Professor
CDAC, M.Sc.IT
STACKS
 Stack is an ordered list of similar data type.
 A stack is an abstract data type that can be
logically thought as linear structure represented
by a real physical stack or pile.
 insertion and deletion of items takes place at
one end called top of the stack.
 The basic implementation of a stack is LIFO
(Last In First Out).
 push() function is used to insert new elements
into the Stack and pop() is used to delete an
element from the stack. Both insertion and
deletion are allowed at only one end of Stack
called Top.
STACKS
STACK AS AN ARRAY
 It is very easy to manage a stack if we represent
it using an array.
 The problem with an array is that we are
required to declare the size of the array before
using it in a program, which makes it a fixed
size structure.
 Stack on the other hand does not have any
fixed size.
 So, an array with a maximum size large enough
to manage stack can be declared.
 As a result, the stack can grow or shrink within
the space reserved for it.
STACKS
Value of top Status of stack
-1 Empty
0 One element
N-1 Full
n overflow
BASIC OPERATIONS ON A STACK
 Push Operation
The process of putting a new data element onto stack
is known as a Push Operation. Push operation
involves a series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and
exit.
Step 3 − If the stack is not full, increments top to
point next empty space.
Step 4 − Adds data element to the stack location,
where top is pointing.
Step 5 − Returns success.
PUSH OPERATION ON A STACK
PUSH FUNCTION IN C
bool isfull()
{
if(top == MAXSIZE)
return true;
else
return false;
}
void push(int data)
{
if(!isFull())
{
top = top + 1;
stack[top] = data;
}
else
{
printf("Could not insert data, Stack is full.n");
}
}
BASIC OPERATIONS ON A STACK AS AN ARRAY
 Pop Operation
Accessing the content while removing it from the stack, is known
as a Pop Operation. In an array implementation of pop()
operation, the data element is not actually removed,
instead top is decremented to a lower position in the stack to
point to the next value. But in linked-list implementation, pop()
actually removes data element and deallocates memory space.
A Pop operation may involve the following steps −
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at
which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
POP OPERATION ON A STACK
POP FUNCTION IN C
bool isempty()
{
if(top == -1)
return true;
else
return false;
}
int pop()
{
if(!isempty())
{
data = stack[top];
top = top - 1;
return data;
}
else
{
printf("Could not retrieve data, Stack is empty.n");
}
}
APPLICATIONS OF A STACK
 The simplest application of a stack is to
reverse a word. You push a given word to
stack - letter by letter - and then pop letters
from the stack.
 Another application is an "undo" mechanism
in text editors; this operation is accomplished
by keeping all text changes in a stack.
 Back and forward buttons of web browsers
STACK USING LINKED LIST
 The major problem with the stack implemented using
array is, it works only for fixed number of data values.
That means the amount of data must be specified at
the beginning of the implementation itself.
 The stack implemented using linked list can work for
unlimited number of values.
 So, there is no need to fix the size at the beginning of
the implementation.
 In linked list implementation of a stack, every new
node is inserted as 'top' element.
 Whenever we want to remove an element from the
stack, simply remove the node which is pointed by
'top' by moving 'top' to its next node in the list.
 The next field of the first element must be
always NULL.
STACK USING LINKED LIST
 The stack as linked list is represented as a
singly connected list.
 We shall push and pop nodes from one end
of a linked list.
 Each node in the linked list contains the data
and a pointer that gives location of the next
node in the list.
STACK USING LINKED LIST
OPERATIONS ON A STACK AS A LINKED LIST
Define a 'Node' structure with two members
Data and next.
Define a Node pointer 'top' and set it
to NULL.
struct Node
{
int data;
struct Node *next;
}*top = NULL;
STACKS USING LINKED LISTS
 push(value) - Inserting an element into the Stack
Create a newNode with given value.
Check whether stack is Empty
if(top == NULL)
If it is Empty, then
newNode → next = NULL.
If it is Not Empty, then
newNode → next = top.
Finally, set top = newNode.
 pop() - Deleting an Element from a Stack
Check whether stack is Empty
if(top == NULL).
If it is Empty, then display "Stack is Empty!!! Deletion is not
possible!!!" and terminate the function
If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
temp=top;
Then set top = top → next.
Finally, delete temp (free(temp)).
STACKS USING LINKED LISTS
 display() - Displaying stack of elements
Check whether stack is Empty
if(top == NULL).
If it is Empty, then display 'Stack is Empty!!!' and terminate the
function.
If it is Not Empty, then define a Node pointer 'temp' and initialize
with top.
temp=top;
Display 'temp → data --->' and move it to the next node. Repeat
the same until temp reaches to the first node in the stack
while (temp → next != NULL)
{
Cout<<temp->data;
temp=temp->next;
}
Finally! Display 'temp → data ---> NULL'.
Cout<<“NULL”;
QUEUE
 Queue is also a collection of similar data
types.
 Queue is a linear data structure in which the
insertion and deletion operations are
performed at two different ends.
 The insertion is performed at one end which
is the ‘rear’ end and deletion is performed at
other end which is known as 'front'.
 the insertion and deletion operations are
performed based on FIFO (First In First
OPERATIONS ON A QUEUE
 The following operations are performed on a queue data
structure...
1. enQueue(value) - (To insert an element into the
queue)
2. deQueue() - (To delete an element from the queue)
3. display() - (To display the elements of the queue)
 Few more functions are required to make the above-
mentioned queue operation efficient. These are −
a) peek() − Gets the element at the front of the queue
without removing it.
int peek()
{
return queue[front];
}
OPERATIONS ON A QUEUE
b) isfull() − Checks if the queue is full.
bool isfull()
{
if(rear == MAXSIZE - 1)
return true;
Else
return false;
}
c) isempty() − Checks if the queue is empty.
bool isempty()
{
if(front < 0 || front > rear)
return true;
else
return false;
}
QUEUE OPERATIONS USING ARRAY
Create a one dimensional array with above
defined SIZE (int queue[SIZE])
Define two integer variables 'front' and 'rear'
and initialize both with '-1'. int front = -1, rear =
-1
 enQueue(value) - Inserting value into the
queue
• Check whether queue is FULL. (rear == SIZE-
1)
• If it is FULL, then display "Queue is FULL!!!
Insertion is not possible!!!" and terminate the
function.
QUEUE OPERATIONS USING ARRAY
 deQueue() - Deleting a value from the Queue
• Check whether queue is EMPTY.
• If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
• If it is NOT EMPTY, then increment the front value by one front
++. Then display queue[front] as deleted element.
• Then check whether both front and rear are equal
(front == rear), if it TRUE, then set both front and rear to '-1'
(front = rear = -1).
display() - Displays the elements of a Queue
• Check whether queue is EMPTY.
• If it is EMPTY, then display "Queue is EMPTY!!!" and terminate
the function.
• If it is NOT EMPTY, then define an integer variable 'i' and set
i = front+1
• Display queue[i] value and increment 'i' value by one i++. Repeat
the same until 'i' value is equal to rear. while (i <= rear)
QUEUE USING LINKED LISTS
 The major problem with the queue
implemented using array is, It will work for
only fixed number of data.
 The queue which is implemented using linked
list can work for unlimited number of values.
 No need to fix the size at beginning of the
implementation.
 In linked list implementation of a queue, the
last inserted node is always pointed by 'rear'
and the first node is always pointed by 'front'.
QUEUE USING LINKED LIST
OPERATIONS ON A QUEUE USING LINKED LIST
• Define a 'Node' structure with two
members data and next.
• Define two Node pointers 'front' and 'rear'
and set both to NULL.
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;
OPERATIONS ON A QUEUE USING LINKED LIST
 enQueue(value) - Inserting an element into the Queue
• Create a newNode with given value and set
• newNode → next = NULL
• Check whether queue is Empty
if(front== NULL)
• If it is Empty then, set front = newNode and rear = newNode.
• If it is Not Empty then, set
• rear → next = newNode and rear = newNode.
deQueue() - Deleting an Element from Queue
• Check whether queue is Empty if front == NULL.
• If it is Empty, then display "Queue is Empty!!! Deletion is not
possible!!!" and terminate from the function
• If it is Not Empty then, define a Node pointer 'temp' and set it to
'front'. temp=front;
• Then set front = front → next and delete temp (free(temp)).
OPERATIONS ON A QUEUE USING LINKED LIST
 display() - Displaying the elements of Queue
• Check whether queue is Empty
if(front == NULL).
• If it is Empty then, display 'Queue is Empty!!!' and terminate
the function.
• If it is Not Empty then, define a Node pointer 'temp' and initialize
with front.
temp=front;
• Display 'temp → data ' and move it to the next node. Repeat the
same until 'temp' reaches to 'rear'
while(temp → next != NULL)
{
cout<<temp->data;
temp=temp->next;
}
Finally! Display NULL
cout<<“NULL”;
CIRCULAR QUEUE
 Circular Queue is a linear data structure
in which the operations are performed
based on FIFO (First In First Out) principle
and the last position is connected back to
the first position to make a circle.
 Note that the container of items is an array.
Array is stored in main memory. Main
memory is linear. So this circularity is only
logical. There can not be physical circularity
in main memory.
CIRCULAR QUEUE
CIRCULAR QUEUE
In a normal Queue Data Structure, we can insert elements
until queue becomes full. But once if queue becomes full, we
can not insert the next element until all the elements are
deleted from the queue.
After inserting all the elements into the queue.
CIRCULAR QUEUE
Now consider the following situation after deleting three
elements from the queue...
This situation also says that Queue is Full and we can not
insert the new element because, 'rear' is still at last position. In
above situation, even though we have empty positions in the
queue we can not make use of them to insert new element.
This is the major problem in normal queue data structure. To
overcome this problem we use circular queue data structure.
CIRCULAR QUEUE
 Addition causes the increment in REAR. It
means that when REAR reaches MAX-1
position then Increment in REAR causes
REAR to reach at first position that is 0.
if( rear == MAX -1 )
rear = 0;
else
rear = rear + 1;
 The short-hand equivalent representation
may be
rear = ( rear + 1) % MAX;
CIRCULAR QUEUE
 Implementation of Circular Queue
Create a one dimensional array with above defined SIZE
(int cQueue[SIZE])
Define two integer variables 'front' and 'rear' and initialize
both with '-1'. (int front = -1, rear = -1)
enQueue(value) - Inserting value into the Circular
Queue
• Check whether queue is FULL.
• ((rear == SIZE-1 && front == 0) || (front == rear))
• If it is FULL, then display "Queue is FULL!!! Insertion is
not possible!!!" and terminate the function.
• If it is NOT FULL, then check rear == SIZE - 1 && front !=
0 if it is TRUE, then set rear =0.
• Increment rear value by one rear++,
set queue[rear] = value and check front ==size -1 if it
is TRUE, then set front = 0.
CIRCULAR QUEUE
 deQueue() - Deleting a value from the Circular
Queue
• Check whether queue is EMPTY.
• (front == -1 && rear == -1)
• If it is EMPTY, then display "Queue is
EMPTY!!! Deletion is not possible!!!" and
terminate the function.
• If it is NOT EMPTY, then display queue[front] as
deleted element and increment the front value
by one front ++.
• Then check whether front == Rear, if it is TRUE,
then set front = rear = -1
• Else check if front==size-1, if TRUE, set front=0
CIRCULAR QUEUE
 display() - Displays the elements of a Circular Queue
• Check whether queue is EMPTY. (front == -1)
• If it is EMPTY, then display "Queue is EMPTY!!!" and
terminate the function.
• If it is NOT EMPTY, then define an integer variable 'i' and
set i = front;
• Check whether front <= rear, if it is TRUE, then display
queue[i] value and increment 'i' value by one i++. Repeat
the same until 'i <= rear' becomes FALSE.
• If 'front <= rear' is FALSE, then display 'queue[i]' value
and increment 'i' value by one (i++). Repeat the same
until'i <= SIZE - 1' becomes FALSE.
• Set i to 0.
• Again display 'cQueue[i]' value and increment i value by
one (i++). Repeat the same until 'i <= rear'
becomes FALSE.
PRIORITY QUEUES
 a priority queue is an abstract data
type which is like a
regular queue or stack data structure, but
where additionally each element has a
"priority" associated with it. In a priority
queue, an element with high priority is served
before an element with low priority. If two
elements have the same priority, they are
served according to their order in the queue.
 A priority queue is different from a "normal"
queue, because instead of being a "first-in-
first-out" data structure, values come out (i.e.
PRIORITY QUEUES
Consider a networking application where server has to respond for
requests from multiple clients using queue data structure. Assume four
requests arrived to the queue in the order of R1 requires 20 units of time,
R2 requires 2 units of time, R3 requires 10 units of time and R4 requires 5
units of time. Queue is as follows...
PRIORITY QUEUES
Now, check waiting time for each request to be
complete.
R1 : 20 units of time
R2 : 22 units of time (R2 must wait till R1 is
complete - 20 units and R2 itself requires 2 units.
Total 22 units)
R3 : 32 units of time (R3 must wait till R2 is
complete - 22 units and R3 itself requires 10 units.
Total 32 units)
R4 : 37 units of time (R4 must wait till R3 is
complete - 35 units and R4 itself requires 5 units.
Total 37 units)
Here, average waiting time for all requests (R1, R2,
R3 and R4) is (20+22+32+37)/4 ≈ 27 units of time.
PRIORITY QUEUES
That means, if we use a normal queue data
structure to serve these requests the average
waiting time for each request is 27 units of time.
Now, consider another way of serving these
requests. If we serve according to their required
amount of time. That means, first we serve R2
which has minimum time required (2) then serve
R4 which has second minimum time required (5)
then serve R3 which has third minimum time
required (10) and finally R1 which has maximum
time required (20).
Now, check waiting time for each request to be
complete.
PRIORITY QUEUES
Now, check waiting time for each request to be
complete.
R2 : 2 units of time
R4 : 7 units of time (R4 must wait till R2 completes
2 units and R4 itself requires 5 units. Total 7 units)
R3 : 17 units of time (R3 must wait till R4 complete
7 units and R3 itself requires 10 units. Total 17
units)
R1 : 37 units of time (R1 must wait till R3 complete
17 units and R1 itself requires 20 units. Total 37
units)
Here, average waiting time for all requests (R1, R2,
R3 and R4) is (2+7+17+37)/4 ≈ 15 units of time.
From above two situations, it is very clear that, by
using second method server can complete all four
APPLICATIONS OF STACKS-
EXPRESSION PARSING
 The way to write arithmetic expression is
known as a notation. An arithmetic
expression can be written in three different but
equivalent notations, i.e., without changing the
essence or output of an expression. These
notations are −
Infix Notation
Prefix (Polish) Notation
Postfix (Reverse-Polish) Notation
These notations are named as how they use
operator in expression.
APPLICATIONS OF STACKS-
EXPRESSION PARSING
 Infix Notation
• We write expression in infix notation, e.g. a - b
+ c, where operators are used in-between
operands.
• Infix notation does not go well with computing
devices.
• An algorithm to process infix notation could be
difficult and costly in terms of time and space
consumption.
• These infix notations are first converted into
either postfix or prefix notations and then
APPLICATIONS OF STACKS-
EXPRESSION PARSING
 Prefix Notation
• In this notation, operator is prefixed to
operands, i.e. operator is written ahead of
operands.
• For example, +ab. This is equivalent to its
infix notation a + b.
• Prefix notation is also known as Polish
Notation.
APPLICATIONS OF STACKS-
EXPRESSION PARSING
 Postfix Notation
• In this notation style, the operator
is postfixed to the operands i.e., the
operator is written after the operands.
• For example, ab+. This is equivalent to its
infix notation a + b.
• This notation style is known as Reversed
Polish Notation.
CONVERSION OF INFIX TO PREFIX
 In Prefix expression operators comes first then
operands : +ab[ operator ab ]
 While converting an infix expression to a prefix one,
first we have to reverse the original string, then find
out the postfix form of that reversed expression and
again reverse the postfix expression to get the prefix
form.
E.g.
Infix : (a–b)/c*(d + e – f / g)
Reverse : (g/f-e+d)*c/(b-a)
postfix : gf/e-d+c*ba-/
prefix : /-ab*c+d-e/fg
CONVERSION OF INFIX TO POSTFIX
 The algorithm for the conversion is as follows :
1. Scan the Infix string from left to right.
2. Initialise an empty stack.
3. If the scanned character is an operand, add it to
the Postfix string.
4. If the scanned character is an operator and if
the stack is empty Push the character to stack.
5. If the scanned character is an opening bracket ‘(‘ then
--Push ‘(‘ to stack
--If any operator appears, move that also to stack
--If closing bracket ‘)’ appears then remove
elements from stack till ‘)’ is removed.
CONVERSION OF INFIX TO POSTFIX
6. If the scanned character is an Operator, and
the stack is not empty, compare the precedence of the
character with the element on top of
the stack (topStack).
if the priority of incoming operator is > (greater), then
push the incoming operator onto the stack
else pop the previous operator from the stack.
7. Repeat this step till all the characters are scanned.
8. After all characters are scanned, we have to add any
character that the stack may have to the Postfix string.
If stack is not empty add topStack to Postfix
string and Pop the stack. Repeat this step as long as
stack is not empty.
9. Return the Postfix string.
EXAMPLE-INFIX TO POSTFIX
Expression Current
Symbol
Stack Output
Comment
A/B^C-D Initial State
NULL
Initially Stack is
Empty
/B^C-D A NULL A Print Operand
B^C-D /
/ A
Push Operator
Onto Stack
^C-D B / AB Print Operand
C-D ^
/^ AB
Push Operator
Onto Stack
because Priority
of ^ is greater
than Current
Topmost Symbol
of Stack i.e ‘/’
-D C /^ ABC Print Operand
EXAMPLE-INFIX TO POSTFIX
Expressio
n
Current
Symbol
Stack Output Comment
D - / ABC^ Step 1 : Now ‘^’ Has Higher
Priority than Incoming Operator
So We have to Pop Topmost
Element .
Step 2 : Remove Topmost
Operator From Stack and Print it
D - NULL ABC^/ Step 1 : Now ‘/’ is topmost
Element of Stack Has Higher
Priority than Incoming Operator
So We have to Pop Topmost
Element again.
Step 2 : Remove Topmost
Operator From Stack and Print it
D - - ABC^/ Now Stack Becomes Empty and
We can Push Operand Onto
Stack
EXAMPLE-INFIX TO POSTFIX
Expression Current
Symbol
Stack Output Comment
NULL D - ABC^/D Print Operand
NULL NULL - ABC^/D- Expression Scanning
Ends but we have still
one more element in
stack so pop it and
display it
EXAMPLES WITH PARENTHESIS
A+(B*C) infix form
A+(BC*) convert the multiplication
A(BC*)+ convert the addition
ABC*+ postfix form
After the portion of expression inside the brackets
has been converted to postfix, it is to be treated
as a single operand.
(A+B)*C infix form
(AB+)*C convert the addition
(AB+)C* convert the multiplication
AB+C* postfix form
EXERCISES TO BE DONE
Infix postfix prefix
1. A+B AB+ +AB
2. A+B-C AB+C- -+ABC
3. (A+B)*(C-D) AB+CD-* *+AB-CD
4. A^B*C-D+E/F/(G+H) AB^C*D-EF/GH+/+ -
*^ABC+D/E/F+GH
5. ((A+B)*C-(D-E))^(F+G) AB+C*DE- -FG+^ ^-*+ABC-
DE+FG
6. A-B/(C*D^E) ABCDE^*/- -A/B*C^DE
POSTFIX TO INFIX CONVERSION
EXAMPLE 1.
EXPRESSION STACK
ABC-+DE-FG-H+/* NULL
BC-+DE-FG-H+/* A
C-+DE-FG-H+/* AB
-+DE-FG-H+/* ABC
+DE-FG-H+/* AB-C
DE-FG-H+/* A+B-C
E-FG-H+/* A+B-CD
-FG-H+/* A+B-CDE
FG-H+/* A+B-CD-E
G-H+/* A+B-CD-EF
-H+/* A+B-CD-EFG
H+/* A+B-CD-EF-G
+/* A+B-CD-EF-GH
/* A+B-CD-EF-G+H
* A+B-CD-E/(F-G+H)
NULL (A+B-C)*(D-E)/(F-G+H)
POSTFIX TO INFIX CONVERSION
 EXAMPLE 2.
EXPRESSION STACK
12*34*+5* NULL
2*34*+5* 1
*34*+5* 12
34*+5* 1*2
4*+5* 1*23
*+5* 1*234
+5* 1*23*4
5* (1*2)+(3*4)
* (1*2)+(3*4)5
NULL (1*2)+(3*4)*5

More Related Content

PPTX
Introduction to stack
PDF
PPTX
Stacks and Queue - Data Structures
PPT
Stacks
PPSX
PPT
DATA STRUCTURES
PPTX
Linked list
PPT
Stack a Data Structure
Introduction to stack
Stacks and Queue - Data Structures
Stacks
DATA STRUCTURES
Linked list
Stack a Data Structure

What's hot (20)

PPSX
Data structure stack&queue basics
PPTX
Java(Polymorphism)
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPT
PPT
Queue Data Structure
PDF
sparse matrix in data structure
PPTX
Standard Template Library
PPT
Java access modifiers
PPTX
Polynomial reppresentation using Linkedlist-Application of LL.pptx
PDF
Heap and heapsort
PPTX
The Stack And Recursion
PPTX
Association agggregation and composition
PPT
Lec 17 heap data structure
PPT
1.1 binary tree
PPTX
Binary search in data structure
PDF
Data_structure using C-Adi.pdf
PPTX
Stack operation algorithms with example
PPTX
Stack and queue
PPTX
Data structure stack&queue basics
Java(Polymorphism)
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Queue Data Structure
sparse matrix in data structure
Standard Template Library
Java access modifiers
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Heap and heapsort
The Stack And Recursion
Association agggregation and composition
Lec 17 heap data structure
1.1 binary tree
Binary search in data structure
Data_structure using C-Adi.pdf
Stack operation algorithms with example
Stack and queue
Ad

Similar to stacks and queues (20)

DOCX
DSA- Unit III- STACK AND QUEUE
PPTX
VCE Unit 03vv.pptx
PDF
04 stacks
PPT
Stack data structures with definition and code
PPTX
Stack data structure
PPTX
Module 2 ppt.pptx
PPTX
Revisiting a data structures in detail with linked list stack and queue
PPTX
The presentation on stack data structure
PPTX
Stacks – Implementation of stack using array and Linked List – Applications o...
PPTX
Abscddnddmdkwkkstack implementation.pptx
PPTX
Stacks in c++
PDF
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
PPT
Data Structures and algorithms using c .ppt
PPTX
Stack and Queue.pptx university exam preparation
PDF
STACK ( LIFO STRUCTURE) - Data Structure
PPTX
Data Structure.pptx
PPTX
Stack and Queue
PPTX
DS UNIT 2 PPT.pptx stack queue representations
PPTX
Data Structures Stack and Queue Data Structures
PDF
DS UNIT 1.pdf
DSA- Unit III- STACK AND QUEUE
VCE Unit 03vv.pptx
04 stacks
Stack data structures with definition and code
Stack data structure
Module 2 ppt.pptx
Revisiting a data structures in detail with linked list stack and queue
The presentation on stack data structure
Stacks – Implementation of stack using array and Linked List – Applications o...
Abscddnddmdkwkkstack implementation.pptx
Stacks in c++
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Data Structures and algorithms using c .ppt
Stack and Queue.pptx university exam preparation
STACK ( LIFO STRUCTURE) - Data Structure
Data Structure.pptx
Stack and Queue
DS UNIT 2 PPT.pptx stack queue representations
Data Structures Stack and Queue Data Structures
DS UNIT 1.pdf
Ad

Recently uploaded (20)

PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Trump Administration's workforce development strategy
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Updated Idioms and Phrasal Verbs in English subject
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Yogi Goddess Pres Conference Studio Updates
Anesthesia in Laparoscopic Surgery in India
Trump Administration's workforce development strategy
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Final Presentation General Medicine 03-08-2024.pptx
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
A systematic review of self-coping strategies used by university students to ...
Final Presentation General Medicine 03-08-2024.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Orientation - ARALprogram of Deped to the Parents.pptx
Complications of Minimal Access Surgery at WLH
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
History, Philosophy and sociology of education (1).pptx
01-Introduction-to-Information-Management.pdf
Updated Idioms and Phrasal Verbs in English subject

stacks and queues

  • 1. DATA STRUCTURES USING C++ Stacks and queues Ekta Vaswani Assistant Professor CDAC, M.Sc.IT
  • 2. STACKS  Stack is an ordered list of similar data type.  A stack is an abstract data type that can be logically thought as linear structure represented by a real physical stack or pile.  insertion and deletion of items takes place at one end called top of the stack.  The basic implementation of a stack is LIFO (Last In First Out).  push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.
  • 4. STACK AS AN ARRAY  It is very easy to manage a stack if we represent it using an array.  The problem with an array is that we are required to declare the size of the array before using it in a program, which makes it a fixed size structure.  Stack on the other hand does not have any fixed size.  So, an array with a maximum size large enough to manage stack can be declared.  As a result, the stack can grow or shrink within the space reserved for it.
  • 5. STACKS Value of top Status of stack -1 Empty 0 One element N-1 Full n overflow
  • 6. BASIC OPERATIONS ON A STACK  Push Operation The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a series of steps − Step 1 − Checks if the stack is full. Step 2 − If the stack is full, produces an error and exit. Step 3 − If the stack is not full, increments top to point next empty space. Step 4 − Adds data element to the stack location, where top is pointing. Step 5 − Returns success.
  • 8. PUSH FUNCTION IN C bool isfull() { if(top == MAXSIZE) return true; else return false; } void push(int data) { if(!isFull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.n"); } }
  • 9. BASIC OPERATIONS ON A STACK AS AN ARRAY  Pop Operation Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value. But in linked-list implementation, pop() actually removes data element and deallocates memory space. A Pop operation may involve the following steps − Step 1 − Checks if the stack is empty. Step 2 − If the stack is empty, produces an error and exit. Step 3 − If the stack is not empty, accesses the data element at which top is pointing. Step 4 − Decreases the value of top by 1. Step 5 − Returns success.
  • 10. POP OPERATION ON A STACK
  • 11. POP FUNCTION IN C bool isempty() { if(top == -1) return true; else return false; } int pop() { if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.n"); } }
  • 12. APPLICATIONS OF A STACK  The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.  Another application is an "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack.  Back and forward buttons of web browsers
  • 13. STACK USING LINKED LIST  The major problem with the stack implemented using array is, it works only for fixed number of data values. That means the amount of data must be specified at the beginning of the implementation itself.  The stack implemented using linked list can work for unlimited number of values.  So, there is no need to fix the size at the beginning of the implementation.  In linked list implementation of a stack, every new node is inserted as 'top' element.  Whenever we want to remove an element from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its next node in the list.  The next field of the first element must be always NULL.
  • 14. STACK USING LINKED LIST  The stack as linked list is represented as a singly connected list.  We shall push and pop nodes from one end of a linked list.  Each node in the linked list contains the data and a pointer that gives location of the next node in the list.
  • 16. OPERATIONS ON A STACK AS A LINKED LIST Define a 'Node' structure with two members Data and next. Define a Node pointer 'top' and set it to NULL. struct Node { int data; struct Node *next; }*top = NULL;
  • 17. STACKS USING LINKED LISTS  push(value) - Inserting an element into the Stack Create a newNode with given value. Check whether stack is Empty if(top == NULL) If it is Empty, then newNode → next = NULL. If it is Not Empty, then newNode → next = top. Finally, set top = newNode.  pop() - Deleting an Element from a Stack Check whether stack is Empty if(top == NULL). If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the function If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'. temp=top; Then set top = top → next. Finally, delete temp (free(temp)).
  • 18. STACKS USING LINKED LISTS  display() - Displaying stack of elements Check whether stack is Empty if(top == NULL). If it is Empty, then display 'Stack is Empty!!!' and terminate the function. If it is Not Empty, then define a Node pointer 'temp' and initialize with top. temp=top; Display 'temp → data --->' and move it to the next node. Repeat the same until temp reaches to the first node in the stack while (temp → next != NULL) { Cout<<temp->data; temp=temp->next; } Finally! Display 'temp → data ---> NULL'. Cout<<“NULL”;
  • 19. QUEUE  Queue is also a collection of similar data types.  Queue is a linear data structure in which the insertion and deletion operations are performed at two different ends.  The insertion is performed at one end which is the ‘rear’ end and deletion is performed at other end which is known as 'front'.  the insertion and deletion operations are performed based on FIFO (First In First
  • 20. OPERATIONS ON A QUEUE  The following operations are performed on a queue data structure... 1. enQueue(value) - (To insert an element into the queue) 2. deQueue() - (To delete an element from the queue) 3. display() - (To display the elements of the queue)  Few more functions are required to make the above- mentioned queue operation efficient. These are − a) peek() − Gets the element at the front of the queue without removing it. int peek() { return queue[front]; }
  • 21. OPERATIONS ON A QUEUE b) isfull() − Checks if the queue is full. bool isfull() { if(rear == MAXSIZE - 1) return true; Else return false; } c) isempty() − Checks if the queue is empty. bool isempty() { if(front < 0 || front > rear) return true; else return false; }
  • 22. QUEUE OPERATIONS USING ARRAY Create a one dimensional array with above defined SIZE (int queue[SIZE]) Define two integer variables 'front' and 'rear' and initialize both with '-1'. int front = -1, rear = -1  enQueue(value) - Inserting value into the queue • Check whether queue is FULL. (rear == SIZE- 1) • If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate the function.
  • 23. QUEUE OPERATIONS USING ARRAY  deQueue() - Deleting a value from the Queue • Check whether queue is EMPTY. • If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and terminate the function. • If it is NOT EMPTY, then increment the front value by one front ++. Then display queue[front] as deleted element. • Then check whether both front and rear are equal (front == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -1). display() - Displays the elements of a Queue • Check whether queue is EMPTY. • If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function. • If it is NOT EMPTY, then define an integer variable 'i' and set i = front+1 • Display queue[i] value and increment 'i' value by one i++. Repeat the same until 'i' value is equal to rear. while (i <= rear)
  • 24. QUEUE USING LINKED LISTS  The major problem with the queue implemented using array is, It will work for only fixed number of data.  The queue which is implemented using linked list can work for unlimited number of values.  No need to fix the size at beginning of the implementation.  In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is always pointed by 'front'.
  • 26. OPERATIONS ON A QUEUE USING LINKED LIST • Define a 'Node' structure with two members data and next. • Define two Node pointers 'front' and 'rear' and set both to NULL. struct Node { int data; struct Node *next; }*front = NULL,*rear = NULL;
  • 27. OPERATIONS ON A QUEUE USING LINKED LIST  enQueue(value) - Inserting an element into the Queue • Create a newNode with given value and set • newNode → next = NULL • Check whether queue is Empty if(front== NULL) • If it is Empty then, set front = newNode and rear = newNode. • If it is Not Empty then, set • rear → next = newNode and rear = newNode. deQueue() - Deleting an Element from Queue • Check whether queue is Empty if front == NULL. • If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from the function • If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'. temp=front; • Then set front = front → next and delete temp (free(temp)).
  • 28. OPERATIONS ON A QUEUE USING LINKED LIST  display() - Displaying the elements of Queue • Check whether queue is Empty if(front == NULL). • If it is Empty then, display 'Queue is Empty!!!' and terminate the function. • If it is Not Empty then, define a Node pointer 'temp' and initialize with front. temp=front; • Display 'temp → data ' and move it to the next node. Repeat the same until 'temp' reaches to 'rear' while(temp → next != NULL) { cout<<temp->data; temp=temp->next; } Finally! Display NULL cout<<“NULL”;
  • 29. CIRCULAR QUEUE  Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle.  Note that the container of items is an array. Array is stored in main memory. Main memory is linear. So this circularity is only logical. There can not be physical circularity in main memory.
  • 31. CIRCULAR QUEUE In a normal Queue Data Structure, we can insert elements until queue becomes full. But once if queue becomes full, we can not insert the next element until all the elements are deleted from the queue. After inserting all the elements into the queue.
  • 32. CIRCULAR QUEUE Now consider the following situation after deleting three elements from the queue... This situation also says that Queue is Full and we can not insert the new element because, 'rear' is still at last position. In above situation, even though we have empty positions in the queue we can not make use of them to insert new element. This is the major problem in normal queue data structure. To overcome this problem we use circular queue data structure.
  • 33. CIRCULAR QUEUE  Addition causes the increment in REAR. It means that when REAR reaches MAX-1 position then Increment in REAR causes REAR to reach at first position that is 0. if( rear == MAX -1 ) rear = 0; else rear = rear + 1;  The short-hand equivalent representation may be rear = ( rear + 1) % MAX;
  • 34. CIRCULAR QUEUE  Implementation of Circular Queue Create a one dimensional array with above defined SIZE (int cQueue[SIZE]) Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1, rear = -1) enQueue(value) - Inserting value into the Circular Queue • Check whether queue is FULL. • ((rear == SIZE-1 && front == 0) || (front == rear)) • If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate the function. • If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then set rear =0. • Increment rear value by one rear++, set queue[rear] = value and check front ==size -1 if it is TRUE, then set front = 0.
  • 35. CIRCULAR QUEUE  deQueue() - Deleting a value from the Circular Queue • Check whether queue is EMPTY. • (front == -1 && rear == -1) • If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and terminate the function. • If it is NOT EMPTY, then display queue[front] as deleted element and increment the front value by one front ++. • Then check whether front == Rear, if it is TRUE, then set front = rear = -1 • Else check if front==size-1, if TRUE, set front=0
  • 36. CIRCULAR QUEUE  display() - Displays the elements of a Circular Queue • Check whether queue is EMPTY. (front == -1) • If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function. • If it is NOT EMPTY, then define an integer variable 'i' and set i = front; • Check whether front <= rear, if it is TRUE, then display queue[i] value and increment 'i' value by one i++. Repeat the same until 'i <= rear' becomes FALSE. • If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i' value by one (i++). Repeat the same until'i <= SIZE - 1' becomes FALSE. • Set i to 0. • Again display 'cQueue[i]' value and increment i value by one (i++). Repeat the same until 'i <= rear' becomes FALSE.
  • 37. PRIORITY QUEUES  a priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue.  A priority queue is different from a "normal" queue, because instead of being a "first-in- first-out" data structure, values come out (i.e.
  • 38. PRIORITY QUEUES Consider a networking application where server has to respond for requests from multiple clients using queue data structure. Assume four requests arrived to the queue in the order of R1 requires 20 units of time, R2 requires 2 units of time, R3 requires 10 units of time and R4 requires 5 units of time. Queue is as follows...
  • 39. PRIORITY QUEUES Now, check waiting time for each request to be complete. R1 : 20 units of time R2 : 22 units of time (R2 must wait till R1 is complete - 20 units and R2 itself requires 2 units. Total 22 units) R3 : 32 units of time (R3 must wait till R2 is complete - 22 units and R3 itself requires 10 units. Total 32 units) R4 : 37 units of time (R4 must wait till R3 is complete - 35 units and R4 itself requires 5 units. Total 37 units) Here, average waiting time for all requests (R1, R2, R3 and R4) is (20+22+32+37)/4 ≈ 27 units of time.
  • 40. PRIORITY QUEUES That means, if we use a normal queue data structure to serve these requests the average waiting time for each request is 27 units of time. Now, consider another way of serving these requests. If we serve according to their required amount of time. That means, first we serve R2 which has minimum time required (2) then serve R4 which has second minimum time required (5) then serve R3 which has third minimum time required (10) and finally R1 which has maximum time required (20). Now, check waiting time for each request to be complete.
  • 41. PRIORITY QUEUES Now, check waiting time for each request to be complete. R2 : 2 units of time R4 : 7 units of time (R4 must wait till R2 completes 2 units and R4 itself requires 5 units. Total 7 units) R3 : 17 units of time (R3 must wait till R4 complete 7 units and R3 itself requires 10 units. Total 17 units) R1 : 37 units of time (R1 must wait till R3 complete 17 units and R1 itself requires 20 units. Total 37 units) Here, average waiting time for all requests (R1, R2, R3 and R4) is (2+7+17+37)/4 ≈ 15 units of time. From above two situations, it is very clear that, by using second method server can complete all four
  • 42. APPLICATIONS OF STACKS- EXPRESSION PARSING  The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are − Infix Notation Prefix (Polish) Notation Postfix (Reverse-Polish) Notation These notations are named as how they use operator in expression.
  • 43. APPLICATIONS OF STACKS- EXPRESSION PARSING  Infix Notation • We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. • Infix notation does not go well with computing devices. • An algorithm to process infix notation could be difficult and costly in terms of time and space consumption. • These infix notations are first converted into either postfix or prefix notations and then
  • 44. APPLICATIONS OF STACKS- EXPRESSION PARSING  Prefix Notation • In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. • For example, +ab. This is equivalent to its infix notation a + b. • Prefix notation is also known as Polish Notation.
  • 45. APPLICATIONS OF STACKS- EXPRESSION PARSING  Postfix Notation • In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. • For example, ab+. This is equivalent to its infix notation a + b. • This notation style is known as Reversed Polish Notation.
  • 46. CONVERSION OF INFIX TO PREFIX  In Prefix expression operators comes first then operands : +ab[ operator ab ]  While converting an infix expression to a prefix one, first we have to reverse the original string, then find out the postfix form of that reversed expression and again reverse the postfix expression to get the prefix form. E.g. Infix : (a–b)/c*(d + e – f / g) Reverse : (g/f-e+d)*c/(b-a) postfix : gf/e-d+c*ba-/ prefix : /-ab*c+d-e/fg
  • 47. CONVERSION OF INFIX TO POSTFIX  The algorithm for the conversion is as follows : 1. Scan the Infix string from left to right. 2. Initialise an empty stack. 3. If the scanned character is an operand, add it to the Postfix string. 4. If the scanned character is an operator and if the stack is empty Push the character to stack. 5. If the scanned character is an opening bracket ‘(‘ then --Push ‘(‘ to stack --If any operator appears, move that also to stack --If closing bracket ‘)’ appears then remove elements from stack till ‘)’ is removed.
  • 48. CONVERSION OF INFIX TO POSTFIX 6. If the scanned character is an Operator, and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). if the priority of incoming operator is > (greater), then push the incoming operator onto the stack else pop the previous operator from the stack. 7. Repeat this step till all the characters are scanned. 8. After all characters are scanned, we have to add any character that the stack may have to the Postfix string. If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. 9. Return the Postfix string.
  • 49. EXAMPLE-INFIX TO POSTFIX Expression Current Symbol Stack Output Comment A/B^C-D Initial State NULL Initially Stack is Empty /B^C-D A NULL A Print Operand B^C-D / / A Push Operator Onto Stack ^C-D B / AB Print Operand C-D ^ /^ AB Push Operator Onto Stack because Priority of ^ is greater than Current Topmost Symbol of Stack i.e ‘/’ -D C /^ ABC Print Operand
  • 50. EXAMPLE-INFIX TO POSTFIX Expressio n Current Symbol Stack Output Comment D - / ABC^ Step 1 : Now ‘^’ Has Higher Priority than Incoming Operator So We have to Pop Topmost Element . Step 2 : Remove Topmost Operator From Stack and Print it D - NULL ABC^/ Step 1 : Now ‘/’ is topmost Element of Stack Has Higher Priority than Incoming Operator So We have to Pop Topmost Element again. Step 2 : Remove Topmost Operator From Stack and Print it D - - ABC^/ Now Stack Becomes Empty and We can Push Operand Onto Stack
  • 51. EXAMPLE-INFIX TO POSTFIX Expression Current Symbol Stack Output Comment NULL D - ABC^/D Print Operand NULL NULL - ABC^/D- Expression Scanning Ends but we have still one more element in stack so pop it and display it
  • 52. EXAMPLES WITH PARENTHESIS A+(B*C) infix form A+(BC*) convert the multiplication A(BC*)+ convert the addition ABC*+ postfix form After the portion of expression inside the brackets has been converted to postfix, it is to be treated as a single operand. (A+B)*C infix form (AB+)*C convert the addition (AB+)C* convert the multiplication AB+C* postfix form
  • 53. EXERCISES TO BE DONE Infix postfix prefix 1. A+B AB+ +AB 2. A+B-C AB+C- -+ABC 3. (A+B)*(C-D) AB+CD-* *+AB-CD 4. A^B*C-D+E/F/(G+H) AB^C*D-EF/GH+/+ - *^ABC+D/E/F+GH 5. ((A+B)*C-(D-E))^(F+G) AB+C*DE- -FG+^ ^-*+ABC- DE+FG 6. A-B/(C*D^E) ABCDE^*/- -A/B*C^DE
  • 54. POSTFIX TO INFIX CONVERSION EXAMPLE 1. EXPRESSION STACK ABC-+DE-FG-H+/* NULL BC-+DE-FG-H+/* A C-+DE-FG-H+/* AB -+DE-FG-H+/* ABC +DE-FG-H+/* AB-C DE-FG-H+/* A+B-C E-FG-H+/* A+B-CD -FG-H+/* A+B-CDE FG-H+/* A+B-CD-E G-H+/* A+B-CD-EF -H+/* A+B-CD-EFG H+/* A+B-CD-EF-G +/* A+B-CD-EF-GH /* A+B-CD-EF-G+H * A+B-CD-E/(F-G+H) NULL (A+B-C)*(D-E)/(F-G+H)
  • 55. POSTFIX TO INFIX CONVERSION  EXAMPLE 2. EXPRESSION STACK 12*34*+5* NULL 2*34*+5* 1 *34*+5* 12 34*+5* 1*2 4*+5* 1*23 *+5* 1*234 +5* 1*23*4 5* (1*2)+(3*4) * (1*2)+(3*4)5 NULL (1*2)+(3*4)*5