SlideShare a Scribd company logo
1 of 24
1
Lecture 9: Stack and Queue
What is a Stack
• Stack of Books
2
Stacks
• What is a Stack?
– A stack is a data structure of ordered items such
that items can be inserted and removed only at
one end.
3
4
Stacks
• What can we do with a stack?
– push - place an item on the stack
– peek - Look at the item on top of the stack,
but do not remove it
– pop - Look at the item on top of the stack
and remove it
5
Stacks
• A stack is a LIFO (Last-In/First-Out) data
structure
• A stack is sometimes also called a
pushdown store.
• What are some applications of stacks?
– Program execution
– Parsing
– Evaluating postfix expressions
6
Stacks
• Problem:
– What happens if we try to pop an item off the
stack when the stack is empty?
• This is called a stack underflow. The pop method
needs some way of telling us that this has happened.
In java we use the java.util.EmptyStackException
Interface IStack
Interface Istack {
boolean empty();
void push(char c);
char pop();
char peek();
}
Using a IStack
• A balance of braces.
– (()) balanced braces
– ()(()()))) not balanced braces
• How can you use Istack to check a brace is
balanced or not?
When you implement the above
requirement, you ignore the
implementation details of Istack.
9
Implementing a Stack
• There are two ways we can implement a
stack:
– Using an array
– Using a linked list
10
Implementing a Stack
• Implementing a stack using an array is
fairly easy.
– The bottom of the stack is at data[0]
– The top of the stack is at data[numItems-1]
– push onto the stack at data[numItems]
– pop off of the stack at data[numItems-1]
11
Implementing a Stack
• Implementing a stack using a linked list
isn’t that bad either…
– Store the items in the stack in a linked list
– The top of the stack is the head node, the
bottom of the stack is the end of the list
– push by adding to the front of the list
– pop by removing from the front of the list
12
Reversing a Word
• We can use a stack to reverse the letters in a
word.
• How?
13
Reversing a Word
• Read each letter in the word and push it
onto the stack
• When you reach the end of the word, pop
the letters off the stack and print them out.
What is a Queue?
14
15
Queues
• What is a queue?
– A data structure of ordered items such that
items can be inserted only at one end and
removed at the other end.
• Example
– A line at the supermarket
16
Queues
• What can we do with a queue?
– Enqueue - Add an item to the queue
– Dequeue - Remove an item from the queue
• These ops are also called insert and getFront
in order to simplify things.
Queues
• A queue is called a FIFO (First in-First out)
data structure.
• What are some applications of queues?
– Round-robin scheduling in processors
– Input/Output processing
– Queueing of packets for delivery in networks
17
18
Implementing a Queue
• Just like a stack, we can implementing a
queue in two ways:
– Using an array
– Using a linked list
19
Implementing a Queue
• Using an array to implement a queue is
significantly harder than using an array to
implement a stack. Why?
– Unlike a stack, where we add and remove at the
same end, in a queue we add to one end and
remove from the other.
20
Implementing a Queue
• There are two options for implementing a
queue using an array:
• Option 1:
– Enqueue at data[0] and shift all of the rest of
the items in the array down to make room.
– Dequeue from data[numItems-1]
21
Implementing a Queue
• Option 2
– Enqueue at data[rear+1]
– Dequeue at data[front]
– The rear variable always contains the index of
the last item in the queue.
– The front variable always contains the index of
the first item in the queue.
– When we reach the end of the array, wrap
around to the front again.
22
Implementing a Queue
// option 2 sketch of insert
insert(Object item) {
if(manyItems == 0) front = rear = 0;
else rear = (rear + 1) mod size;
data[rear] = item;
manyItems++;
}
23
Implementing a Queue
// option 2 sketch of getFront
Object getFront() {
answer = data[front];
front = (front + 1) mod size;
manyItems--;
return answer
}
24
Implementing a Queue
• Implementing a queue using a linked list is
still easy:
– Front of the queue is stored as the head node of
the linked list, rear of the queue is stored as the
tail node.
– Enqueue by adding to the end of the list
– Dequeue by removing from the front of the list.

More Related Content

Similar to Stack and Queue Data Structures Explained

Similar to Stack and Queue Data Structures Explained (20)

Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptx
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
STACK.pptx
STACK.pptxSTACK.pptx
STACK.pptx
 
Queues
Queues Queues
Queues
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
Stacks
StacksStacks
Stacks
 
Stacks
StacksStacks
Stacks
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
Data structures
Data structuresData structures
Data structures
 
Data Structure - Stack.pptx
Data Structure - Stack.pptxData Structure - Stack.pptx
Data Structure - Stack.pptx
 
STACKS AND QUEUES.pptx
STACKS AND QUEUES.pptxSTACKS AND QUEUES.pptx
STACKS AND QUEUES.pptx
 
STACKS AND QUEUES.pptx
STACKS AND QUEUES.pptxSTACKS AND QUEUES.pptx
STACKS AND QUEUES.pptx
 
Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computer
 
Data structure.pdf
Data structure.pdfData structure.pdf
Data structure.pdf
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)
 
stack.pptx
stack.pptxstack.pptx
stack.pptx
 
Data Structures
Data StructuresData Structures
Data Structures
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Stacks
StacksStacks
Stacks
 

More from MuhammadSheraz836877 (20)

Quick & Merge Sort.ppt
Quick & Merge Sort.pptQuick & Merge Sort.ppt
Quick & Merge Sort.ppt
 
Bubble Sort.ppt
Bubble Sort.pptBubble Sort.ppt
Bubble Sort.ppt
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
 
CHAPTER 1 BASIC sql STATEMENTS.pptx
CHAPTER 1 BASIC sql STATEMENTS.pptxCHAPTER 1 BASIC sql STATEMENTS.pptx
CHAPTER 1 BASIC sql STATEMENTS.pptx
 
Sortings .pptx
Sortings .pptxSortings .pptx
Sortings .pptx
 
Articles Eng.ppt
Articles Eng.pptArticles Eng.ppt
Articles Eng.ppt
 
FORMS OF MATTER.pptx
FORMS OF MATTER.pptxFORMS OF MATTER.pptx
FORMS OF MATTER.pptx
 
Bonds of solids.pptx
Bonds of solids.pptxBonds of solids.pptx
Bonds of solids.pptx
 
Infinitives_by_M._Sheraz.PPT
Infinitives_by_M._Sheraz.PPTInfinitives_by_M._Sheraz.PPT
Infinitives_by_M._Sheraz.PPT
 
articles.ppt
articles.pptarticles.ppt
articles.ppt
 
Speakingskills. Ppt
Speakingskills. PptSpeakingskills. Ppt
Speakingskills. Ppt
 
speakingskills. Ppt
speakingskills. Pptspeakingskills. Ppt
speakingskills. Ppt
 
voice-techniques. Ppt
voice-techniques. Pptvoice-techniques. Ppt
voice-techniques. Ppt
 
body language. Ppt
body language. Pptbody language. Ppt
body language. Ppt
 
latchesandflipflops.ppt
latchesandflipflops.pptlatchesandflipflops.ppt
latchesandflipflops.ppt
 
listeningskills.ppt
listeningskills.pptlisteningskills.ppt
listeningskills.ppt
 
listeningskills.ppt
listeningskills.pptlisteningskills.ppt
listeningskills.ppt
 
listeningskills.ppt
listeningskills.pptlisteningskills.ppt
listeningskills.ppt
 
Business Econimics.ppt
Business Econimics.pptBusiness Econimics.ppt
Business Econimics.ppt
 
latchesflip-flop DLD
latchesflip-flop DLDlatchesflip-flop DLD
latchesflip-flop DLD
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

Stack and Queue Data Structures Explained

  • 1. 1 Lecture 9: Stack and Queue
  • 2. What is a Stack • Stack of Books 2
  • 3. Stacks • What is a Stack? – A stack is a data structure of ordered items such that items can be inserted and removed only at one end. 3
  • 4. 4 Stacks • What can we do with a stack? – push - place an item on the stack – peek - Look at the item on top of the stack, but do not remove it – pop - Look at the item on top of the stack and remove it
  • 5. 5 Stacks • A stack is a LIFO (Last-In/First-Out) data structure • A stack is sometimes also called a pushdown store. • What are some applications of stacks? – Program execution – Parsing – Evaluating postfix expressions
  • 6. 6 Stacks • Problem: – What happens if we try to pop an item off the stack when the stack is empty? • This is called a stack underflow. The pop method needs some way of telling us that this has happened. In java we use the java.util.EmptyStackException
  • 7. Interface IStack Interface Istack { boolean empty(); void push(char c); char pop(); char peek(); }
  • 8. Using a IStack • A balance of braces. – (()) balanced braces – ()(()()))) not balanced braces • How can you use Istack to check a brace is balanced or not? When you implement the above requirement, you ignore the implementation details of Istack.
  • 9. 9 Implementing a Stack • There are two ways we can implement a stack: – Using an array – Using a linked list
  • 10. 10 Implementing a Stack • Implementing a stack using an array is fairly easy. – The bottom of the stack is at data[0] – The top of the stack is at data[numItems-1] – push onto the stack at data[numItems] – pop off of the stack at data[numItems-1]
  • 11. 11 Implementing a Stack • Implementing a stack using a linked list isn’t that bad either… – Store the items in the stack in a linked list – The top of the stack is the head node, the bottom of the stack is the end of the list – push by adding to the front of the list – pop by removing from the front of the list
  • 12. 12 Reversing a Word • We can use a stack to reverse the letters in a word. • How?
  • 13. 13 Reversing a Word • Read each letter in the word and push it onto the stack • When you reach the end of the word, pop the letters off the stack and print them out.
  • 14. What is a Queue? 14
  • 15. 15 Queues • What is a queue? – A data structure of ordered items such that items can be inserted only at one end and removed at the other end. • Example – A line at the supermarket
  • 16. 16 Queues • What can we do with a queue? – Enqueue - Add an item to the queue – Dequeue - Remove an item from the queue • These ops are also called insert and getFront in order to simplify things.
  • 17. Queues • A queue is called a FIFO (First in-First out) data structure. • What are some applications of queues? – Round-robin scheduling in processors – Input/Output processing – Queueing of packets for delivery in networks 17
  • 18. 18 Implementing a Queue • Just like a stack, we can implementing a queue in two ways: – Using an array – Using a linked list
  • 19. 19 Implementing a Queue • Using an array to implement a queue is significantly harder than using an array to implement a stack. Why? – Unlike a stack, where we add and remove at the same end, in a queue we add to one end and remove from the other.
  • 20. 20 Implementing a Queue • There are two options for implementing a queue using an array: • Option 1: – Enqueue at data[0] and shift all of the rest of the items in the array down to make room. – Dequeue from data[numItems-1]
  • 21. 21 Implementing a Queue • Option 2 – Enqueue at data[rear+1] – Dequeue at data[front] – The rear variable always contains the index of the last item in the queue. – The front variable always contains the index of the first item in the queue. – When we reach the end of the array, wrap around to the front again.
  • 22. 22 Implementing a Queue // option 2 sketch of insert insert(Object item) { if(manyItems == 0) front = rear = 0; else rear = (rear + 1) mod size; data[rear] = item; manyItems++; }
  • 23. 23 Implementing a Queue // option 2 sketch of getFront Object getFront() { answer = data[front]; front = (front + 1) mod size; manyItems--; return answer }
  • 24. 24 Implementing a Queue • Implementing a queue using a linked list is still easy: – Front of the queue is stored as the head node of the linked list, rear of the queue is stored as the tail node. – Enqueue by adding to the end of the list – Dequeue by removing from the front of the list.