SlideShare a Scribd company logo
SHUNMUGAVADIVOO.T,
ASST PROFESSOR,
DEPARTMENT OF COMPUTER SCIENCE,
S.A.COLLEGE OF ARTS & SCIENCE,
CHENNAI – 600077
TAMILNADU
DATA STRUCTURE – STACK AND QUEUE
UNIT 2
DATA
STRUCTURES
1
The stack abstract data type is defined by the following structure and
operations. A stack is structured, as described above, as an ordered collection of
items where items are added to and removed from the end called the “top.”
Stacks are ordered LIFO.
Primitive Stack Operations
Stack operations may involve initializing the stack, using it and then de-
initializing it. Apart from these basic stuffs, a stack is used for the following two
primary operations −
push() − Pushing (storing) an element on the stack.
pop() − Removing (accessing) an element from the stack.
3
THE STACK ABSTRACT
DATA TYPE
PRIMITIVE STACK
OPERATIONS
The following diagram depicts a stack and its operations −
4
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.
7
POP
OPERATION
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.
8
Algorithm of Push and Pop Operation
7
PUS H
begin procedure push: stack,
data
if stack is full
return null
endif top ← top + 1
stack[top] ← data
end procedure
Pop
begin procedure pop: stack
if stack is empty
return null
endif data ← stack[top]
top ← top – 1
return data
end procedure
ARRAY
REPRESENTATION OF
STACK
Stack can be represented by means of a one way list or a linear array.
A pointer variable top contains the locations of the top element of
the stack and a variable max stk gives the maximum number of
elements of the Stack that can be held by Stack.
the condition top=0 will indicate that the stack is empty.
This procedure pushes an item onto the Stack via Top.
PUSH(Stack, Top, MaxStk, Item)
1. If Top = = MaxStk //check Stack already fill or not
then print "Overflow" and return
2. Set Top = Top + 1 //increase top by 1
3.Stack[Top] = Item //insert item in new top position 4. Return
Let MaxStk=8, the array Stack contains M, N, O in it. Perform
operations on it
8
ARRAY REPRESENTATION OF
STACK
Pop operation on Stack
This procedures deletes the top element of Stack and assigns
it to the variable item.
POP(Stack, top, Item)
1.If Top = = Null //check Stack top element to be deleted is
empty
then print "Underflow" and return
2. Item = Stack[Top] //assign top element to item
3. Set Top = Top - 1 //decrease top by 1
4. Return
pop 3 elements
11
REPRESENTATION OF
STACK
• Each node in the stack should contain two parts:
– info: the user's data
– next: the address of the next element in the stack
12
Node Type
template<class ItemType>
struct NodeType {
ItemType info;
NodeType* next;
};
LINKED
REPRESENTATION OF
STACK
First and last stack elements
We need a data member to store the pointer to the top of the
stack
The next element of the last node should contain the
value NULL
11
APPLICATIONS OF
STACKS
1)Reversing Strings:
• A simple application of stack is reversing strings.To reverse a
string , the characters of string are pushed onto the stack one by one
as the string
is read from left to right.
•Once all the characters of string are pushed onto stack, they are
popped one by one. Since the character last pushed in comes out
first, subsequent pop
operation results in the reversal of the string.
For example:
To reverse the string ‘REVERSE’ the string is
read from left to right and its characters are
pushed . LIKE:
12
APPLICATIONS OF
STACKS
2)Evaluating arithmetic expressions:
• INFIX notation:
The general way of writing arithmetic
expressions is known as infix notation.
e.g, (a+b)
• PREFIX notation:
e.g, + A B
• POSTFIX notation:
e.g: A B +
Conversion of INFIX to POSTFIX conversion:
Example: 2+(4-1)*3 step1
2+41-*3 step2
2+41-3*
step3 241-
3*+ step4
13
CONVERSION OF INFIX INTO
POSTFIX 2+(4-1)*3 INTO
241-3*+
14
APPLICATIONS OF
STACKS
15
3) CONVERSION OF INFIX INTO POSTFIX EXPRESSION
•
•
•
•
•
Output operands as encountered
Stack left parentheses
When ‘)’
– repeat
• pop stack, output
symbol
– until ‘(‘
•‘(‘ is poped but not output
If symbol +, *, or ‘(‘
– pop stack until entry of
lower priority or ‘(‘
• ‘(‘ removed only when
matching ‘)’ is processed
– push symbol into stack
At end of input, pop stack until
empty
ALGORITHM TO EVALUATE A
POSTFIX EXPRESSION
16
•
•
•
Use a stack, assume binary operators +,*
Input: postfix expression
Scan the input
– If operand,
• push to stack
– If operator
• pop the stack twice
• apply operator
• push result back to stack
QUEUE
17
Stores a set of elements in a particular
order Queue principle: FIRST IN
FIRST OUT= FIFO
It means: the first element inserted is the first one
to be removed
Example
The first one in line is the first one to be served.
FIRST IN
FIRST OUT
18
rear
front
C
B
A
rear
front
D
C
B
A
rear
front
ARRAY-BASED QUEUE
IMPLEMENTATION
• As with the array-based stack
implementation, the array is of fixed size
–A queue of maximum N elements
Slightly more complicated
– Need to maintain track of both
front and rear
•
Implementation 1
Implementation 2
19
IMPLEMENTATION
enqueue
void enqueue(int *rear,
element item)
{
/* add an item to the queue */
if (*rear = =
MAX_QUEUE_SIZE_1) {
queue_full( );
return;
}
queue [++*rear]
= item;
}
Dequeue
element dequeue(int *front,
int rear)
{
/* remove element at the
front of the queue */
if ( *front = = rear)
return
queue_empty( );
/* return an error key */
return queue [ + + *front];
}
23
IMPLEMENTING QUEUES USING
LINKED LISTS
21
•
•
•
Allocate memory for each new element
dynamically
Link the queue elements together
Use two pointers, qFront and qRear, to mark the
front and rear of the queue
TOWER OF HANOI
22
•
•
•
•
•
•
•
There are three towers
3 gold disks, with decreasing sizes, placed on the first
tower
You need to move all of the disks from the first tower
to the last tower
Larger disks can not be placed on top of smaller disks
The third tower can be used to temporarily hold disks
The disks must be moved within one week. Assume
one disk can be moved in 1 second. Is this possible?
To create an algorithm to solve this problem, it is
convenient to generalize the problem to the “N-disk”
problem, where in our case N = 3.
RECURSIVE
SOLUTION
23
RECURSIVE SOLUTION
27
Circular Queue
EMPTY QUEUE
25
Leave one empty space when queue is full
Why?
26
ABSTRACT DATA TYPE:
PRIORITY QUEUE
• A priority queue is a collection of zero or more items,
– associated with each item is a priority
• A priority queue has at least three operations
– insert(item i) (enqueue) a new item
– delete() (dequeue) the member with the highest
priority
– find() the item with the highest priority
– decreasePriority(item i, p) decrease the priority
of ith item to p
• Note that in a priority queue "first in first out" does not apply in general.
30
PRIORITY QUEUES:
ASSUMPTIONS
• The highest priority can be either the minimum
value of all the items, or the maximum.
– We will assume the highest priority is the
minimum.
– Call the delete operation deleteMin().
– Call the find operation findMin().
• Assume the priority queue has n members
31

More Related Content

PPTX
The presentation on stack data structure
gaurav77712
 
PDF
Chapter 5 Stack and Queue.pdf
GirT2
 
PPTX
DSVIDEO.pptx data structure for bca and bsc cs students to higher
shunmugavadivoot
 
PPT
week 7,8,10,11 alll files included from .ppt
LidetAdmassu
 
PPTX
Chapter 5-stack.pptx
Halid Assen
 
PPTX
Stack
Ashish Ranjan
 
PPTX
Stack and Queue.pptx university exam preparation
RAtna29
 
PPT
Stacks
sweta dargad
 
The presentation on stack data structure
gaurav77712
 
Chapter 5 Stack and Queue.pdf
GirT2
 
DSVIDEO.pptx data structure for bca and bsc cs students to higher
shunmugavadivoot
 
week 7,8,10,11 alll files included from .ppt
LidetAdmassu
 
Chapter 5-stack.pptx
Halid Assen
 
Stack and Queue.pptx university exam preparation
RAtna29
 
Stacks
sweta dargad
 

Similar to DS UNIT 2 PPT.pptx stack queue representations (20)

PPT
Data structure lecture7
Kumar
 
PPTX
VCE Unit 03vv.pptx
skilljiolms
 
PPTX
DSEC1.pptx stack exchange communities that I am not 🚭 hi nahi
ganesh209832
 
PPTX
DS-UNIT 3 FINAL.pptx
prakashvs7
 
PPTX
Stack data structure
rogineojerio020496
 
PDF
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
PPTX
Stacks and queues using aaray line .pptx
ramkumar649780
 
PDF
LEC3-DS ALGO(updated).pdf
MuhammadUmerIhtisham
 
PPTX
stacks and queues
EktaVaswani2
 
PDF
Stacks-and-Queues.pdf
TobyWtf
 
PPT
Stack data structures with definition and code
bansidharj11
 
PPTX
Abscddnddmdkwkkstack implementation.pptx
zainshahid3040
 
PPTX
Stack and its Applications : Data Structures ADT
Soumen Santra
 
PPTX
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
PPTX
Module 2 ppt.pptx
SonaPathak4
 
PPT
Difference between stack and queue
Pulkitmodi1998
 
PPTX
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
PPTX
Unit 3 stack
Dabbal Singh Mahara
 
PPTX
Data Structures Stack and Queue Data Structures
poongothai11
 
PDF
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
Data structure lecture7
Kumar
 
VCE Unit 03vv.pptx
skilljiolms
 
DSEC1.pptx stack exchange communities that I am not 🚭 hi nahi
ganesh209832
 
DS-UNIT 3 FINAL.pptx
prakashvs7
 
Stack data structure
rogineojerio020496
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
Stacks and queues using aaray line .pptx
ramkumar649780
 
LEC3-DS ALGO(updated).pdf
MuhammadUmerIhtisham
 
stacks and queues
EktaVaswani2
 
Stacks-and-Queues.pdf
TobyWtf
 
Stack data structures with definition and code
bansidharj11
 
Abscddnddmdkwkkstack implementation.pptx
zainshahid3040
 
Stack and its Applications : Data Structures ADT
Soumen Santra
 
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Module 2 ppt.pptx
SonaPathak4
 
Difference between stack and queue
Pulkitmodi1998
 
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
Unit 3 stack
Dabbal Singh Mahara
 
Data Structures Stack and Queue Data Structures
poongothai11
 
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
Ad

Recently uploaded (20)

PDF
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
CDH. pptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
CDH. pptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
Ad

DS UNIT 2 PPT.pptx stack queue representations

  • 1. SHUNMUGAVADIVOO.T, ASST PROFESSOR, DEPARTMENT OF COMPUTER SCIENCE, S.A.COLLEGE OF ARTS & SCIENCE, CHENNAI – 600077 TAMILNADU DATA STRUCTURE – STACK AND QUEUE
  • 3. The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. Primitive Stack Operations Stack operations may involve initializing the stack, using it and then de- initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations − push() − Pushing (storing) an element on the stack. pop() − Removing (accessing) an element from the stack. 3 THE STACK ABSTRACT DATA TYPE
  • 4. PRIMITIVE STACK OPERATIONS The following diagram depicts a stack and its operations − 4
  • 5. 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. 7
  • 6. POP OPERATION 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. 8
  • 7. Algorithm of Push and Pop Operation 7 PUS H begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure Pop begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top – 1 return data end procedure
  • 8. ARRAY REPRESENTATION OF STACK Stack can be represented by means of a one way list or a linear array. A pointer variable top contains the locations of the top element of the stack and a variable max stk gives the maximum number of elements of the Stack that can be held by Stack. the condition top=0 will indicate that the stack is empty. This procedure pushes an item onto the Stack via Top. PUSH(Stack, Top, MaxStk, Item) 1. If Top = = MaxStk //check Stack already fill or not then print "Overflow" and return 2. Set Top = Top + 1 //increase top by 1 3.Stack[Top] = Item //insert item in new top position 4. Return Let MaxStk=8, the array Stack contains M, N, O in it. Perform operations on it 8
  • 9. ARRAY REPRESENTATION OF STACK Pop operation on Stack This procedures deletes the top element of Stack and assigns it to the variable item. POP(Stack, top, Item) 1.If Top = = Null //check Stack top element to be deleted is empty then print "Underflow" and return 2. Item = Stack[Top] //assign top element to item 3. Set Top = Top - 1 //decrease top by 1 4. Return pop 3 elements 11
  • 10. REPRESENTATION OF STACK • Each node in the stack should contain two parts: – info: the user's data – next: the address of the next element in the stack 12 Node Type template<class ItemType> struct NodeType { ItemType info; NodeType* next; };
  • 11. LINKED REPRESENTATION OF STACK First and last stack elements We need a data member to store the pointer to the top of the stack The next element of the last node should contain the value NULL 11
  • 12. APPLICATIONS OF STACKS 1)Reversing Strings: • A simple application of stack is reversing strings.To reverse a string , the characters of string are pushed onto the stack one by one as the string is read from left to right. •Once all the characters of string are pushed onto stack, they are popped one by one. Since the character last pushed in comes out first, subsequent pop operation results in the reversal of the string. For example: To reverse the string ‘REVERSE’ the string is read from left to right and its characters are pushed . LIKE: 12
  • 13. APPLICATIONS OF STACKS 2)Evaluating arithmetic expressions: • INFIX notation: The general way of writing arithmetic expressions is known as infix notation. e.g, (a+b) • PREFIX notation: e.g, + A B • POSTFIX notation: e.g: A B + Conversion of INFIX to POSTFIX conversion: Example: 2+(4-1)*3 step1 2+41-*3 step2 2+41-3* step3 241- 3*+ step4 13
  • 14. CONVERSION OF INFIX INTO POSTFIX 2+(4-1)*3 INTO 241-3*+ 14
  • 15. APPLICATIONS OF STACKS 15 3) CONVERSION OF INFIX INTO POSTFIX EXPRESSION • • • • • Output operands as encountered Stack left parentheses When ‘)’ – repeat • pop stack, output symbol – until ‘(‘ •‘(‘ is poped but not output If symbol +, *, or ‘(‘ – pop stack until entry of lower priority or ‘(‘ • ‘(‘ removed only when matching ‘)’ is processed – push symbol into stack At end of input, pop stack until empty
  • 16. ALGORITHM TO EVALUATE A POSTFIX EXPRESSION 16 • • • Use a stack, assume binary operators +,* Input: postfix expression Scan the input – If operand, • push to stack – If operator • pop the stack twice • apply operator • push result back to stack
  • 17. QUEUE 17 Stores a set of elements in a particular order Queue principle: FIRST IN FIRST OUT= FIFO It means: the first element inserted is the first one to be removed Example The first one in line is the first one to be served.
  • 19. ARRAY-BASED QUEUE IMPLEMENTATION • As with the array-based stack implementation, the array is of fixed size –A queue of maximum N elements Slightly more complicated – Need to maintain track of both front and rear • Implementation 1 Implementation 2 19
  • 20. IMPLEMENTATION enqueue void enqueue(int *rear, element item) { /* add an item to the queue */ if (*rear = = MAX_QUEUE_SIZE_1) { queue_full( ); return; } queue [++*rear] = item; } Dequeue element dequeue(int *front, int rear) { /* remove element at the front of the queue */ if ( *front = = rear) return queue_empty( ); /* return an error key */ return queue [ + + *front]; } 23
  • 21. IMPLEMENTING QUEUES USING LINKED LISTS 21 • • • Allocate memory for each new element dynamically Link the queue elements together Use two pointers, qFront and qRear, to mark the front and rear of the queue
  • 22. TOWER OF HANOI 22 • • • • • • • There are three towers 3 gold disks, with decreasing sizes, placed on the first tower You need to move all of the disks from the first tower to the last tower Larger disks can not be placed on top of smaller disks The third tower can be used to temporarily hold disks The disks must be moved within one week. Assume one disk can be moved in 1 second. Is this possible? To create an algorithm to solve this problem, it is convenient to generalize the problem to the “N-disk” problem, where in our case N = 3.
  • 26. Leave one empty space when queue is full Why? 26
  • 27. ABSTRACT DATA TYPE: PRIORITY QUEUE • A priority queue is a collection of zero or more items, – associated with each item is a priority • A priority queue has at least three operations – insert(item i) (enqueue) a new item – delete() (dequeue) the member with the highest priority – find() the item with the highest priority – decreasePriority(item i, p) decrease the priority of ith item to p • Note that in a priority queue "first in first out" does not apply in general. 30
  • 28. PRIORITY QUEUES: ASSUMPTIONS • The highest priority can be either the minimum value of all the items, or the maximum. – We will assume the highest priority is the minimum. – Call the delete operation deleteMin(). – Call the find operation findMin(). • Assume the priority queue has n members 31