SlideShare a Scribd company logo
1 of 42
Download to read offline
Creating Structures with
Abstract Data Types
• It is often convenient to describe
algorithms and data structures in
terms of the operations
performed
– rather than in terms of details of
implementation.
• We separate the “concept” from
a particular implementation.
Abstract Data Types (ADT)
• Why use ADTs?
– Organisation & reducing
complexity
– Ease of coding
– Controlling how your data may
be accessed by a user
Abstract Data Types (ADT)
Stacks and Queues (and variations) are structures
that are frequently used in programs and often use
arrays as the underlying structure:
For example:
A queue of things todo if creating a todo list app.
A stack of web pages visited to go back in a web
browser.
5
Queue concepts
• Illustration (queue of persons):
BUS
STOP
6
Queue concepts
• A queue is a first-in-first-out sequence
of elements.
• Elements can be added only at one end
(the rear of the queue) and removed
only at the other end (the front of the
queue).
• The length/size of a queue is the
number of elements it contains.
• An empty queue has length zero.
Queue ADT: requirements
• Requirements:
1) It must be possible to make a queue empty.
2) It must be possible to test whether a queue is
empty.
3) It must be possible to obtain the length of a
queue.
4) It must be possible to add an element at the rear
of a queue.
5) It must be possible to remove the front element
from a queue.
6) It must be possible to access the front element in
a queue without removing it.
It must be possible to obtain the length of a queue.
It must be possible to make a queue empty.
It must be possible to test whether a queue is empty.
A function is needed that will set the values in the array to
a value that signifies it is clear and set the front and back
of the queue to the first index of the array.
A function is required that will test if the queue is empty.
A function or value is required that will keep track of
the number of values in the array.
It must be possible to access the front element in a queue
without removing it.
It must be possible to add an element at the rear of a
queue.
It must be possible to remove the front element from a
queue.
a function is needed that will add an element to the array. The
position of the next element will need to be marked. What if we
reach the end of the array?
A function is required that will allow the removal of an element. The
end of the queue will need to be re-set to the next position. What
happens when you reach the end of the queue?
A function is required that will read the top element value.
int []MyQueue = new int[5];
The Queue: Visualisation
MyQueue
4
0 1 2 3
MyQueue
Initialisation Length = 0
4
0 1 2 3
Front = 0
Back = 0
front back
MyQueue
addtoqueue
6
Assign item to array[back]
Increment back
Increment Length
4
0 1 2 3
Front = 0
Back = 1
Length = 1
front back
MyQueue
addtoqueue
6
Assign item to array[back]
Increment back
Increment Length
4
0 1 2 3
Front = 0
Back = 2
length = 2
5
front back
Remove from queue
MyQueue 6
Increment front
decrement length
4
0 1 2 3
Front = 1
Back = 2
length = 1
5
front back
Add to queue?
MyQueue 6
4
0 1 2 3
Front = 3
Back = 0
length = 2
5 4
7 8
Assign item to array[back]
Increment back
Increment length
If back = array length (i.e. 5)
Set back to 0
The array is not full but we have reached
the length of the array
front
back
MyQueue 12
4
0 1 2 3
Front = 3
Back = 1
length = 3
5 4
7 8
Add to queue
Assign item to array[back]
Increment back
Increment length
If back = array length
Set back to 0
MyQueue 12
4
0 1 2 3
Front = 3
Back = 3
length = 5
3 46 7 8
Add to queue?
Assign item to array[back]
Increment back
Increment length
If back = array length
Set back to 0
If array full
exit
MyQueue
Remove an item
Size = 0
Increment front
decrement length
If length == 0
exit
else
MyQueue 12
4
0 1 2 3
3 46 7 8
Remove an item
Front = 4
Increment front
decrement size
If length == 0
exit
else
If front = array length
set front to 0
• Possible contract:
/////////////// Accessors ///////////////
boolean isEmpty();
// Return true if and only if this queue is empty.
int size();
// Return this queue’s length.
int getFirst();
// Return the element at the front of this queue.
/////////////// Modifiers ///////////////
void clear();
// Make this queue empty.
void addLast(int elem);
// Add elem as the rear element of this queue.
int removeFirst();
// Remove and return the front element of this queue.
• Java implementation:
public class Queue
private int[] elems;
private int front, rear, length;
/////////////// Constructor ///////////////
public Queue (int maxLength) {
elems = new int[maxLength];
front = rear = length = 0;
}
• Java implementation (continued):
public boolean isEmpty () {
return (length == 0);
}
public int size () {
return length;
}
public int getFirst () {
if (length == 0) throw …;
return elems[front];
}
public void clear () {
front = rear = length = 0;
}
public void addLast (int elem) {
if (length == elems.length) throw …;
elems[rear++] = elem;
if (rear == elems.length) rear = 0;
length++;
}
public int removeFirst () {
if (length == 0) throw …;
int frontElem = elems[front];
front++;
if (front == elems.length)
front = 0;
return frontElem;
}
}
25
Stack concepts (1)
• A stack is a last-in-first-out sequence of
elements.
• Elements can added and removed only
at one end (the top of the stack).
• The depth of stack is the number of
elements it contains.
• An empty stack has depth zero.
26
Stack concepts (2)
• Illustration (stack of books):
Moby Dick
War & Peace
Rob Roy
Initially:
Moby Dick
War & Peace
After remov-
ing a book:
Moby Dick
War & Peace
Misérables
After adding
“Misérables”:
Moby Dick
War & Peace
Misérables
2001
After adding
“2001”:
Stack ADT: requirements
• Requirements:
1) It must be possible to make a stack empty.
2) It must be possible to add (‘push’) an element to
the top of a stack.
3) It must be possible to remove (‘pop’) the topmost
element from a stack.
4) It must be possible to test whether a stack is
empty.
5) It should be possible to access the topmost
element in a stack without removing it.
It must be possible to make a stack empty.
A function is needed that will set the values in the array to a value that
signifies it is clear and set the top of the stack to the first index of
the array
It must be possible to add (‘push’) an element to the
top of a stack.
a function is needed that will add an element to the array. The
position of the next element will need to be marked. What if we
reach the end of the array?
It must be possible to remove (‘pop’) the topmost
element from a stack.
A function is required that will allow the removal of an element. The
top of the stack will need to be re-set to the next position. What
happens when you reach the end of the stack?
It must be possible to test whether a
stack is empty.
It should be possible to access the topmost
element in a stack without removing it.
A function is required that will test if the stack is
empty – a counter will be required that will keep
track of the number of elements in the array.
A function is required that will read the top
element value.
• The stack: visualisation
• 1. create the stack
int []MyStack = new int[5];
[1]
[2]
[3]
[4]
Memory
[0]
MyStack
Top element
represents the
element position at
the top of the stack
Depth 0
Depth is the
position that the
next element
will be added
to. It is also the
number of the
elements in the
array.
initialise top_element to -1?
Memory
MyStack
Add/push an item on the stack
5
Top_element 0
Depth 1
Top
element
Assign element
to depth position
Increment depth
Increment top
element
[1]
[2]
[3]
[4]
[0]
Memory
MyStack
Add/push an item on the stack
5
We now have a stack of:
top_element 1
Depth 2
10
Top
element
Assign element to
depth position
Increment depth
Increment top element
depth
[1]
[2]
[3]
[4]
[0]
Memory
MyStack
pop an item from the stack
Depth 1
Top-element 0
Top
element
decrement the top element
Decrement depth
5
depth
[1]
[2]
[3]
[4]
[0]
Memory
MyStack
push an item from the stack
We now have a stack of:
Top_element 3
Depth 4
10
Top
element
5 Assign the element
increment depth
4
16
depth
[1]
[2]
[3]
[4]
[0]
[1]
[2]
[3]
[4]
Memory
[0]
MyStack
push an item from the stack
We now have a stack of:
Top_element 4
Depth 5
10
Top
element
5
If depth = array length
stack full
Else
Assign the element
increment depth
4
16
depth
6
[1]
[2]
[3]
[4]
Memory
[0]
MyStack
Depth 0
Pop from an empty stack
decrement the top
element
Decrement depth
If stack not empty
• Points to note:
• To read the top most element without removing
– If the array is not empty
• Return array[topelement]
• To test whether a stack is full:
– Size will be the same as array.length
• To make a stack empty
– Set depth to 0
Set Topelement to -1?
• To test whether a stack is empty:
• Depth will be 0
Stack ADT: contract
• Possible contract
/////////////// Accessors ///////////////
bool isEmpty();
// Return true if and only if this stack is empty.
int getTop();
// Return the message at the top of this stack.
/////////////// Modifiers ///////////////
void clear();
// Make this stack empty.
void push(int elem);
// Add elem as the top element of this stack.
int pop();
// Remove and return the element at the top of this
stack.
Implementation using arrays
• Java implementation:
public class Stack {
private int[] elems;
private int depth;
/////////////// Constructor ///////////////
public Stack (int maxDepth) {
elems = new int[maxDepth];
depth = 0;
}
Implementation using arrays
/////////////// Accessors ///////////////
public boolean isEmpty () {
return (depth == 0);
}
public int getTop () {
if (depth == 0)
error(“stack empty”);
else
return elems[depth-1];
}
Implementation using arrays
/////////////// Modifiers ///////////////
public void clear() {
depth = 0;
}
public void push(int elem) {
if (depth == elems.Length)
error(“Stack full”);
else
elems[depth++] = elem;
}
public int pop() {
if (depth == 0)
error(“Stack empty”);
else{
String topElem = elems[--depth];
return topElem;
}
}
Implementation using arrays

More Related Content

Similar to CEN 235 4. Abstract Data Types - Queue and Stack.pdf

stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmstack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmxadihe1593
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptxsinghprpg
 
23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-dequesRishabh Jindal
 
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 computerabinathsabi
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptxskilljiolms
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - NotesOmprakash Chauhan
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queuePulkitmodi1998
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptxSonaPathak4
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using Ccpjcollege
 

Similar to CEN 235 4. Abstract Data Types - Queue and Stack.pdf (20)

Stacks queues
Stacks queuesStacks queues
Stacks queues
 
Queues
Queues Queues
Queues
 
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmstack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptx
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-deques
 
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
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Queue
QueueQueue
Queue
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

CEN 235 4. Abstract Data Types - Queue and Stack.pdf

  • 2. • It is often convenient to describe algorithms and data structures in terms of the operations performed – rather than in terms of details of implementation. • We separate the “concept” from a particular implementation. Abstract Data Types (ADT)
  • 3. • Why use ADTs? – Organisation & reducing complexity – Ease of coding – Controlling how your data may be accessed by a user Abstract Data Types (ADT)
  • 4. Stacks and Queues (and variations) are structures that are frequently used in programs and often use arrays as the underlying structure: For example: A queue of things todo if creating a todo list app. A stack of web pages visited to go back in a web browser.
  • 5. 5 Queue concepts • Illustration (queue of persons): BUS STOP
  • 6. 6 Queue concepts • A queue is a first-in-first-out sequence of elements. • Elements can be added only at one end (the rear of the queue) and removed only at the other end (the front of the queue). • The length/size of a queue is the number of elements it contains. • An empty queue has length zero.
  • 7. Queue ADT: requirements • Requirements: 1) It must be possible to make a queue empty. 2) It must be possible to test whether a queue is empty. 3) It must be possible to obtain the length of a queue. 4) It must be possible to add an element at the rear of a queue. 5) It must be possible to remove the front element from a queue. 6) It must be possible to access the front element in a queue without removing it.
  • 8. It must be possible to obtain the length of a queue. It must be possible to make a queue empty. It must be possible to test whether a queue is empty. A function is needed that will set the values in the array to a value that signifies it is clear and set the front and back of the queue to the first index of the array. A function is required that will test if the queue is empty. A function or value is required that will keep track of the number of values in the array.
  • 9. It must be possible to access the front element in a queue without removing it. It must be possible to add an element at the rear of a queue. It must be possible to remove the front element from a queue. a function is needed that will add an element to the array. The position of the next element will need to be marked. What if we reach the end of the array? A function is required that will allow the removal of an element. The end of the queue will need to be re-set to the next position. What happens when you reach the end of the queue? A function is required that will read the top element value.
  • 10. int []MyQueue = new int[5]; The Queue: Visualisation MyQueue 4 0 1 2 3
  • 11. MyQueue Initialisation Length = 0 4 0 1 2 3 Front = 0 Back = 0 front back
  • 12. MyQueue addtoqueue 6 Assign item to array[back] Increment back Increment Length 4 0 1 2 3 Front = 0 Back = 1 Length = 1 front back
  • 13. MyQueue addtoqueue 6 Assign item to array[back] Increment back Increment Length 4 0 1 2 3 Front = 0 Back = 2 length = 2 5 front back
  • 14. Remove from queue MyQueue 6 Increment front decrement length 4 0 1 2 3 Front = 1 Back = 2 length = 1 5 front back
  • 15. Add to queue? MyQueue 6 4 0 1 2 3 Front = 3 Back = 0 length = 2 5 4 7 8 Assign item to array[back] Increment back Increment length If back = array length (i.e. 5) Set back to 0 The array is not full but we have reached the length of the array front back
  • 16. MyQueue 12 4 0 1 2 3 Front = 3 Back = 1 length = 3 5 4 7 8 Add to queue Assign item to array[back] Increment back Increment length If back = array length Set back to 0
  • 17. MyQueue 12 4 0 1 2 3 Front = 3 Back = 3 length = 5 3 46 7 8 Add to queue? Assign item to array[back] Increment back Increment length If back = array length Set back to 0 If array full exit
  • 18. MyQueue Remove an item Size = 0 Increment front decrement length If length == 0 exit else
  • 19. MyQueue 12 4 0 1 2 3 3 46 7 8 Remove an item Front = 4 Increment front decrement size If length == 0 exit else If front = array length set front to 0
  • 20. • Possible contract: /////////////// Accessors /////////////// boolean isEmpty(); // Return true if and only if this queue is empty. int size(); // Return this queue’s length. int getFirst(); // Return the element at the front of this queue. /////////////// Modifiers /////////////// void clear(); // Make this queue empty. void addLast(int elem); // Add elem as the rear element of this queue. int removeFirst(); // Remove and return the front element of this queue.
  • 21. • Java implementation: public class Queue private int[] elems; private int front, rear, length; /////////////// Constructor /////////////// public Queue (int maxLength) { elems = new int[maxLength]; front = rear = length = 0; }
  • 22. • Java implementation (continued): public boolean isEmpty () { return (length == 0); } public int size () { return length; } public int getFirst () { if (length == 0) throw …; return elems[front]; }
  • 23. public void clear () { front = rear = length = 0; } public void addLast (int elem) { if (length == elems.length) throw …; elems[rear++] = elem; if (rear == elems.length) rear = 0; length++; }
  • 24. public int removeFirst () { if (length == 0) throw …; int frontElem = elems[front]; front++; if (front == elems.length) front = 0; return frontElem; } }
  • 25. 25 Stack concepts (1) • A stack is a last-in-first-out sequence of elements. • Elements can added and removed only at one end (the top of the stack). • The depth of stack is the number of elements it contains. • An empty stack has depth zero.
  • 26. 26 Stack concepts (2) • Illustration (stack of books): Moby Dick War & Peace Rob Roy Initially: Moby Dick War & Peace After remov- ing a book: Moby Dick War & Peace Misérables After adding “Misérables”: Moby Dick War & Peace Misérables 2001 After adding “2001”:
  • 27. Stack ADT: requirements • Requirements: 1) It must be possible to make a stack empty. 2) It must be possible to add (‘push’) an element to the top of a stack. 3) It must be possible to remove (‘pop’) the topmost element from a stack. 4) It must be possible to test whether a stack is empty. 5) It should be possible to access the topmost element in a stack without removing it.
  • 28. It must be possible to make a stack empty. A function is needed that will set the values in the array to a value that signifies it is clear and set the top of the stack to the first index of the array It must be possible to add (‘push’) an element to the top of a stack. a function is needed that will add an element to the array. The position of the next element will need to be marked. What if we reach the end of the array? It must be possible to remove (‘pop’) the topmost element from a stack. A function is required that will allow the removal of an element. The top of the stack will need to be re-set to the next position. What happens when you reach the end of the stack?
  • 29. It must be possible to test whether a stack is empty. It should be possible to access the topmost element in a stack without removing it. A function is required that will test if the stack is empty – a counter will be required that will keep track of the number of elements in the array. A function is required that will read the top element value.
  • 30. • The stack: visualisation • 1. create the stack int []MyStack = new int[5]; [1] [2] [3] [4] Memory [0] MyStack Top element represents the element position at the top of the stack Depth 0 Depth is the position that the next element will be added to. It is also the number of the elements in the array. initialise top_element to -1?
  • 31. Memory MyStack Add/push an item on the stack 5 Top_element 0 Depth 1 Top element Assign element to depth position Increment depth Increment top element [1] [2] [3] [4] [0]
  • 32. Memory MyStack Add/push an item on the stack 5 We now have a stack of: top_element 1 Depth 2 10 Top element Assign element to depth position Increment depth Increment top element depth [1] [2] [3] [4] [0]
  • 33. Memory MyStack pop an item from the stack Depth 1 Top-element 0 Top element decrement the top element Decrement depth 5 depth [1] [2] [3] [4] [0]
  • 34. Memory MyStack push an item from the stack We now have a stack of: Top_element 3 Depth 4 10 Top element 5 Assign the element increment depth 4 16 depth [1] [2] [3] [4] [0]
  • 35. [1] [2] [3] [4] Memory [0] MyStack push an item from the stack We now have a stack of: Top_element 4 Depth 5 10 Top element 5 If depth = array length stack full Else Assign the element increment depth 4 16 depth 6
  • 36. [1] [2] [3] [4] Memory [0] MyStack Depth 0 Pop from an empty stack decrement the top element Decrement depth If stack not empty
  • 37. • Points to note: • To read the top most element without removing – If the array is not empty • Return array[topelement] • To test whether a stack is full: – Size will be the same as array.length • To make a stack empty – Set depth to 0 Set Topelement to -1? • To test whether a stack is empty: • Depth will be 0
  • 38. Stack ADT: contract • Possible contract /////////////// Accessors /////////////// bool isEmpty(); // Return true if and only if this stack is empty. int getTop(); // Return the message at the top of this stack. /////////////// Modifiers /////////////// void clear(); // Make this stack empty. void push(int elem); // Add elem as the top element of this stack. int pop(); // Remove and return the element at the top of this stack.
  • 39. Implementation using arrays • Java implementation: public class Stack { private int[] elems; private int depth; /////////////// Constructor /////////////// public Stack (int maxDepth) { elems = new int[maxDepth]; depth = 0; }
  • 40. Implementation using arrays /////////////// Accessors /////////////// public boolean isEmpty () { return (depth == 0); } public int getTop () { if (depth == 0) error(“stack empty”); else return elems[depth-1]; }
  • 41. Implementation using arrays /////////////// Modifiers /////////////// public void clear() { depth = 0; } public void push(int elem) { if (depth == elems.Length) error(“Stack full”); else elems[depth++] = elem; }
  • 42. public int pop() { if (depth == 0) error(“Stack empty”); else{ String topElem = elems[--depth]; return topElem; } } Implementation using arrays