SlideShare a Scribd company logo
1 of 50
Stacks and Queues
2 struct Node{
double data;
Node* next;
};
class List {
public:
List(); // constructor
List(const List& list); // copy constructor
~List(); // destructor
List& operator=(const List& list); // assignment operator
bool empty() const; // boolean function
void addHead(double x); // add to the head
double deleteHead(); // delete the head and get the head element
// List& rest(); // get the rest of the list with the head removed
// double headElement() const; // get the head element
void addEnd(double x); // add to the end
double deleteEnd(); // delete the end and get the end element
// double endElement(); // get the element at the end
bool searchNode(double x); // search for a given x
void insertNode(double x); // insert x in a sorted list
void deleteNode(double x); // delete x in a sorted list
…
void print() const; // output
int length() const; // count the number of elements
private:
Node* head;
};
More complete list ADT
3
Stack Overview
Stack ADT
Basic operations of stack
Pushing, popping etc.
Implementations of stacks using
array
linked list
4
Stack
A stack is a list in which insertion and deletion take
place at the same end
This end is called top
The other end is called bottom
Stacks are known as LIFO (Last In, First Out) lists.
The last element inserted will be the first to be retrieved
5
Push and Pop
Primary operations: Push and Pop
Push
Add an element to the top of the stack
Pop
Remove the element at the top of the stack
top
empty stack
A
top
push an element
top
push another
A
B
top
pop
A
6
Implementation of Stacks
Any list implementation could be used to
implement a stack
Arrays (static: the size of stack is given initially)
Linked lists (dynamic: never become full)
We will explore implementations based on
array and linked list
7
class Stack {
public:
Stack(); // constructor
Stack(const Stack& stack); // copy constructor
~Stack(); // destructor
bool empty() const;
void push(const double x);
double pop(); // change the stack
double top() const; // keep the stack unchanged
// bool full(); // optional
// void print() const;
private:
…
};
Stack ADT
update,
‘logical’ constructor/destructor,
composition/decomposition
‘physical’
constructor/destructor
Compare with List, see that it’s ‘operations’ that define the type!
inspection,
access
8
Using Stack
int main(void) {
Stack stack;
stack.push(5.0);
stack.push(6.5);
stack.push(-3.0);
stack.push(-8.0);
stack.print();
cout << "Top: " << stack.top() << endl;
stack.pop();
cout << "Top: " << stack.top() << endl;
while (!stack.empty()) stack.pop();
stack.print();
return 0;
}
result
9
struct Node{
public:
double data;
Node* next;
};
class Stack {
public:
Stack(); // constructor
Stack(const Stack& stack); // copy constructor
~Stack(); // destructor
bool empty() const;
void push(const double x);
double pop(); // change the stack
bool full(); // unnecessary for linked lists
double top() const; // keep the stack unchanged
void print() const;
private:
Node* top;
};
Stack using linked lists
10
void List::addHead(int newdata){
Nodeptr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = head;
head = newPtr;
}
void Stack::push(double x){
Node* newPtr = new Node;
newPtr->data = x;
newPtr->next = top;
top = newPtr;
}
From ‘addHead’ to ‘push’
Push (addHead), Pop (deleteHead)
11
Implementation based on ‘existing’
linked lists
Optional to learn 
Good to see that we may ‘re-use’ linked lists
12
Now let’s implement a stack based on a linked list
To make the best out of the code of List, we implement Stack
by inheriting List
To let Stack access private member head, we make Stack
as a friend of List
class List {
public:
List() { head = NULL; } // constructor
~List(); // destructor
bool empty() { return head == NULL; }
Node* insertNode(int index, double x);
int deleteNode(double x);
int searchNode(double x);
void printList(void);
private:
Node* head;
friend class Stack;
};
13
class Stack : public List {
public:
Stack() {}
~Stack() {}
double top() {
if (head == NULL) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return head->data;
}
void push(const double x) { InsertNode(0, x); }
double pop() {
if (head == NULL) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
double val = head->data;
DeleteNode(val);
return val;
}
}
void printStack() { printList(); }
};
Note: the stack
implementation
based on a linked
list will never be full.
from List
14
Stack using arrays
class Stack {
public:
Stack(int size = 10); // constructor
~Stack() { delete [] values; } // destructor
bool empty() { return top == -1; }
void push(const double x);
double pop();
bool full() { return top == maxTop; }
double top();
void print();
private:
int maxTop; // max stack size = size - 1
int top; // current top of stack
double* values; // element array
};
15
Attributes of Stack
maxTop: the max size of stack
top: the index of the top element of stack
values: point to an array which stores elements of stack
Operations of Stack
empty: return true if stack is empty, return false otherwise
full: return true if stack is full, return false otherwise
top: return the element at the top of stack
push: add an element to the top of stack
pop: delete the element at the top of stack
print: print all the data in the stack
16
Allocate a stack array of size. By default,
size = 10.
Initially top is set to -1. It means the stack is empty.
When the stack is full, top will have its maximum value, i.e.
size – 1.
Stack::Stack(int size /*= 10*/) {
values = new double[size];
top = -1;
maxTop = size - 1;
}
Although the constructor dynamically allocates the stack array,
the stack is still static. The size is fixed after the initialization.
Stack constructor
17
void push(const double x);
Push an element onto the stack
Note top always represents the index of the top
element. After pushing an element, increment top.
void Stack::push(const double x) {
if (full()) // if stack is full, print error
cout << "Error: the stack is full." << endl;
else
values[++top] = x;
}
18
double pop()
Pop and return the element at the top of the stack
Don’t forgot to decrement top
double Stack::pop() {
if (empty()) { //if stack is empty, print error
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
return values[top--];
}
}
19
double top()
Return the top element of the stack
Unlike pop, this function does not remove the top
element
double Stack::top() {
if (empty()) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return values[top];
}
20
void print()
Print all the elements
void Stack::print() {
cout << "top -->";
for (int i = top; i >= 0; i--)
cout << "t|t" << values[i] << "t|" << endl;
cout << "t|---------------|" << endl;
}
21
Stack Application:
Balancing Symbols
To check that every right brace, bracket, and
parentheses must correspond to its left counterpart
e.g. [( )] is legal, but [( ] ) is illegal
Algorithm
(1) Make an empty stack.
(2) Read characters until end of file
i. If the character is an opening symbol, push it onto the stack
ii. If it is a closing symbol, then if the stack is empty, report an error
iii. Otherwise, pop the stack. If the symbol popped is not the
corresponding opening symbol, then report an error
(3) At end of file, if the stack is not empty, report an error
22
Stack Application: function calls and
recursion
Take the example of factorial! And run it.
#include <iostream>
using namespace std;
int fac(int n){
int product;
if(n <= 1) product = 1;
else product = n * fac(n-1);
return product;
}
void main(){
int number;
cout << "Enter a positive integer : " << endl;;
cin >> number;
cout << fac(number) << endl;
}
23
Assume the number typed is 3.
fac(3): has the final returned value 6
3<=1 ? No.
product3 = 3*fac(2) product3=3*2=6, return 6,
fac(2):
2<=1 ? No.
product2 = 2*fac(1) product2=2*1=2, return 2,
fac(1):
1<=1 ? Yes.
return 1
Tracing the program …
24
fac(3) prod3=3*fac(2)
prod2=2*fac(1)fac(2)
fac(1) prod1=1
Call is to ‘push’ and return is to ‘pop’!
top
25
Array versus
linked list implementations
push, pop, top are all constant-time
operations in both array and linked list
implementation
For array implementation, the operations are
performed in very fast constant time
26
Queue Overview
Queue ADT
Basic operations of queue
Enqueuing, dequeuing etc.
Implementation of queue
Linked list
Array
27
Queue
A queue is also a list. However, insertion is
done at one end, while deletion is performed
at the other end.
It is “First In, First Out (FIFO)” order.
Like customers standing in a check-out line in a
store, the first customer in is the first customer
served.
28
Enqueue and Dequeue
Primary queue operations: Enqueue and Dequeue
Like check-out lines in a store, a queue has a front
and a rear.
Enqueue – insert an element at the rear of the
queue
Dequeue – remove an element from the front of
the queue
Insert
(Enqueue)
Remove
(Dequeue) rearfront
29
Implementation of Queue
Just as stacks can be implemented as arrays
or linked lists, so with queues.
Dynamic queues have the same advantages
over static queues as dynamic stacks have
over static stacks
30
class Queue {
public:
Queue();
Queue(Queue& queue);
~Queue();
bool empty();
void enqueue(double x);
double dequeue();
void print(void);
// bool full(); // optional
private:
…
};
Queue ADT
‘physical’ constructor/destructor
‘logical’ constructor/destructor
31
Using Queueint main(void) {
Queue queue;
cout << "Enqueue 5 items." << endl;
for (int x = 0; x < 5; x++)
queue.enqueue(x);
cout << "Now attempting to enqueue again..." << endl;
queue.enqueue(5);
queue.print();
double value;
value=queue.dequeue();
cout << "Retrieved element = " << value << endl;
queue.print();
queue.enqueue(7);
queue.print();
return 0;
}
32
Struct Node {
double data;
Node* next;
}
class Queue {
public:
Queue();
Queue(Queue& queue);
~Queue();
bool empty();
void enqueue(double x);
double dequeue();
// bool full(); // optional
void print(void);
private:
Node* front; // pointer to front node
Node* rear; // pointer to last node
int counter; // number of elements
};
Queue using linked lists
33
class Queue {
public:
Queue() { // constructor
front = rear = NULL;
counter = 0;
}
~Queue() { // destructor
double value;
while (!empty()) dequeue(value);
}
bool empty() {
if (counter) return false;
else return true;
}
void enqueue(double x);
double dequeue();
// bool full() {return false;};
void print(void);
private:
Node* front; // pointer to front node
Node* rear; // pointer to last node
int counter; // number of elements, not compulsary
};
Implementation of some online member
functions …
34
Enqueue (addEnd)
void Queue::enqueue(double x) {
Node* newNode = new Node;
newNode->data = x;
newNode->next = NULL;
if (empty()) {
front = newNode;
}
else {
rear->next = newNode;
}
rear = newNode;
counter++;
}
8
rear
rear
newNode
5
58
35
Dequeue (deleteHead)
double Queue::dequeue() {
double x;
if (empty()) {
cout << "Error: the queue is empty." << endl;
exit(1); // return false;
}
else {
x = front->data;
Node* nextNode = front->next;
delete front;
front = nextNode;
counter--;
}
return x;
}
front
583
8 5
front
36
Printing all the elements
void Queue::print() {
cout << "front -->";
Node* currNode = front;
for (int i = 0; i < counter; i++) {
if (i == 0) cout << "t";
else cout << "tt";
cout << currNode->data;
if (i != counter - 1)
cout << endl;
else
cout << "t<-- rear" << endl;
currNode = currNode->next;
}
}
37
Queue using Arrays
There are several different algorithms to
implement Enqueue and Dequeue
Naïve way
When enqueuing, the front index is always fixed
and the rear index moves forward in the array.
front
rear
Enqueue(3)
3
front
rear
Enqueue(6)
3 6
front
rear
Enqueue(9)
3 6 9
38
Naïve way (cont’d)
When dequeuing, the front index is fixed, and the
element at the front the queue is removed. Move
all the elements after it by one position.
(Inefficient!!!)
Dequeue()
front
rear
6 9
Dequeue() Dequeue()
front
rear
9
rear = -1
front
39
A better way
When enqueued, the rear index moves forward.
When dequeued, the front index also moves forward
by one element
XXXXOOOOO (rear)
OXXXXOOOO (after 1 dequeue, and 1 enqueue)
OOXXXXXOO (after another dequeue, and 2 enqueues)
OOOOXXXXX (after 2 more dequeues, and 2 enqueues)
(front)
The problem here is that the rear index cannot move beyond the
last element in the array.
40
Using Circular Arrays
Using a circular array
When an element moves past the end of a circular
array, it wraps around to the beginning, e.g.
OOOOO7963  4OOOO7963 (after Enqueue(4))
How to detect an empty or full queue, using a
circular array algorithm?
Use a counter of the number of elements in the queue.
41
class Queue {
public:
Queue(int size = 10); // constructor
Queue(Queue& queue); // not necessary!
~Queue() { delete [] values; } // destructor
bool empty(void);
void enqueue(double x); // or bool enqueue();
double dequeue();
bool full();
void print(void);
private:
int front; // front index
int rear; // rear index
int counter; // number of elements
int maxSize; // size of array queue
double* values; // element array
};
full() is not essential, can be embedded
42
Attributes of Queue
front/rear: front/rear index
counter: number of elements in the queue
maxSize: capacity of the queue
values: point to an array which stores elements of the queue
Operations of Queue
empty: return true if queue is empty, return false otherwise
full: return true if queue is full, return false otherwise
enqueue: add an element to the rear of queue
dequeue: delete the element at the front of queue
print: print all the data
43
Queue constructor
Queue(int size = 10)
Allocate a queue array of size. By default, size = 10.
front is set to 0, pointing to the first element of the
array
rear is set to -1. The queue is empty initially.
Queue::Queue(int size /* = 10 */) {
values = new double[size];
maxSize = size;
front = 0;
rear = -1;
counter = 0;
}
44
Empty & Full
Since we keep track of the number of elements
that are actually in the queue: counter, it is
easy to check if the queue is empty or full.
bool Queue::empty() {
if (counter==0) return true;
else return false;
}
bool Queue::full() {
if (counter < maxSize) return false;
else return true;
}
45
Enqueue
void Queue::enqueue(double x) {
if (full()) {
cout << "Error: the queue is full." << endl;
exit(1); // return false;
}
else {
// calculate the new rear position (circular)
rear = (rear + 1) % maxSize;
// insert new item
values[rear] = x;
// update counter
counter++;
// return true;
}
}
Or ‘bool’ if you want
46
Dequeue
double Queue::dequeue() {
double x;
if (empty()) {
cout << "Error: the queue is empty." << endl;
exit(1); // return false;
}
else {
// retrieve the front item
x = values[front];
// move front
front = (front + 1) % maxSize;
// update counter
counter--;
// return true;
}
return x;
}
47
Printing the elements
void Queue::print() {
cout << "front -->";
for (int i = 0; i < counter; i++) {
if (i == 0) cout << "t";
else cout << "tt";
cout << values[(front + i) % maxSize];
if (i != counter - 1)
cout << endl;
else
cout << "t<-- rear" << endl;
}
}
48
Using Queueint main(void) {
Queue queue;
cout << "Enqueue 5 items." << endl;
for (int x = 0; x < 5; x++)
queue.enqueue(x);
cout << "Now attempting to enqueue again..." << endl;
queue.enqueue(5);
queue.print();
double value;
value=queue.dequeue();
cout << "Retrieved element = " << value << endl;
queue.print();
queue.enqueue(7);
queue.print();
return 0;
}
49
Results
Queue implemented using linked list will be never full!
based on array based on linked list
50
Queue applications
When jobs are sent to a printer, in order of
arrival, a queue.
Customers at ticket counters …

More Related Content

What's hot

Single linked list
Single linked listSingle linked list
Single linked listSayantan Sur
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingDavid Muñoz Díaz
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerDavid Muñoz Díaz
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Ruslan Shevchenko
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
The Ring programming language version 1.5.1 book - Part 77 of 180
The Ring programming language version 1.5.1 book - Part 77 of 180The Ring programming language version 1.5.1 book - Part 77 of 180
The Ring programming language version 1.5.1 book - Part 77 of 180Mahmoud Samir Fayed
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftTomohiro Kumagai
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentialsAlexander Granin
 

What's hot (16)

Single linked list
Single linked listSingle linked list
Single linked list
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 
Svitla talks 2021_03_25
Svitla talks 2021_03_25Svitla talks 2021_03_25
Svitla talks 2021_03_25
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
The Ring programming language version 1.5.1 book - Part 77 of 180
The Ring programming language version 1.5.1 book - Part 77 of 180The Ring programming language version 1.5.1 book - Part 77 of 180
The Ring programming language version 1.5.1 book - Part 77 of 180
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftSwift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentials
 
Javascript
JavascriptJavascript
Javascript
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 

Viewers also liked

Data preprocessing
Data preprocessingData preprocessing
Data preprocessingJames Wong
 
Linear Inequalities.pdf
Linear Inequalities.pdfLinear Inequalities.pdf
Linear Inequalities.pdfbwlomas
 
Magazine advert analysis
Magazine advert analysis Magazine advert analysis
Magazine advert analysis sianolivia
 
Scatterplots and trend lines
Scatterplots and trend linesScatterplots and trend lines
Scatterplots and trend linesbwlomas
 
5-1 and 5-2 Quiz - Start 5-3.pdf
5-1 and 5-2 Quiz - Start 5-3.pdf5-1 and 5-2 Quiz - Start 5-3.pdf
5-1 and 5-2 Quiz - Start 5-3.pdfbwlomas
 
Isosceles and Equilateral Triangles.pdf
Isosceles and Equilateral Triangles.pdfIsosceles and Equilateral Triangles.pdf
Isosceles and Equilateral Triangles.pdfbwlomas
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonJames Wong
 
Campus news feed
Campus news feedCampus news feed
Campus news feedNoopur Koli
 
Text categorization as a graph
Text categorization as a graphText categorization as a graph
Text categorization as a graphYoung Alista
 

Viewers also liked (15)

Cache recap
Cache recapCache recap
Cache recap
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Lab%201
Lab%201Lab%201
Lab%201
 
Linear Inequalities.pdf
Linear Inequalities.pdfLinear Inequalities.pdf
Linear Inequalities.pdf
 
Magazine advert analysis
Magazine advert analysis Magazine advert analysis
Magazine advert analysis
 
Scatterplots and trend lines
Scatterplots and trend linesScatterplots and trend lines
Scatterplots and trend lines
 
5-1 and 5-2 Quiz - Start 5-3.pdf
5-1 and 5-2 Quiz - Start 5-3.pdf5-1 and 5-2 Quiz - Start 5-3.pdf
5-1 and 5-2 Quiz - Start 5-3.pdf
 
Isosceles and Equilateral Triangles.pdf
Isosceles and Equilateral Triangles.pdfIsosceles and Equilateral Triangles.pdf
Isosceles and Equilateral Triangles.pdf
 
Gm theory
Gm theoryGm theory
Gm theory
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Campus news feed
Campus news feedCampus news feed
Campus news feed
 
Object model
Object modelObject model
Object model
 
Text categorization as a graph
Text categorization as a graphText categorization as a graph
Text categorization as a graph
 
Xml stylus studio
Xml stylus studioXml stylus studio
Xml stylus studio
 
List and iterator
List and iteratorList and iterator
List and iterator
 

Similar to Stack queue

Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfarorastores
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdffsenterprises
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructuresmartha leon
 
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docx
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docxAdd functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docx
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docxWilliamZnlMarshallc
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docxadkinspaige22
 
Link list part 2
Link list part 2Link list part 2
Link list part 2Anaya Zafar
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfsales98
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 

Similar to Stack queue (20)

Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructures
 
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docx
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docxAdd functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docx
Add functions push(int n- Deque &dq) and pop(Deque &dq)- Functions pus.docx
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
 
Link list part 2
Link list part 2Link list part 2
Link list part 2
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdf
 
Stacks
StacksStacks
Stacks
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 

More from James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtosJames Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningJames Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryJames Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningJames Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksJames Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceJames Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheJames Wong
 
Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisJames Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJames Wong
 
Learning python
Learning pythonLearning python
Learning pythonJames Wong
 

More from James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Recursion
RecursionRecursion
Recursion
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Inheritance
InheritanceInheritance
Inheritance
 
Api crash
Api crashApi crash
Api crash
 
Learning python
Learning pythonLearning python
Learning python
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Stack queue

  • 2. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor List& operator=(const List& list); // assignment operator bool empty() const; // boolean function void addHead(double x); // add to the head double deleteHead(); // delete the head and get the head element // List& rest(); // get the rest of the list with the head removed // double headElement() const; // get the head element void addEnd(double x); // add to the end double deleteEnd(); // delete the end and get the end element // double endElement(); // get the element at the end bool searchNode(double x); // search for a given x void insertNode(double x); // insert x in a sorted list void deleteNode(double x); // delete x in a sorted list … void print() const; // output int length() const; // count the number of elements private: Node* head; }; More complete list ADT
  • 3. 3 Stack Overview Stack ADT Basic operations of stack Pushing, popping etc. Implementations of stacks using array linked list
  • 4. 4 Stack A stack is a list in which insertion and deletion take place at the same end This end is called top The other end is called bottom Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved
  • 5. 5 Push and Pop Primary operations: Push and Pop Push Add an element to the top of the stack Pop Remove the element at the top of the stack top empty stack A top push an element top push another A B top pop A
  • 6. 6 Implementation of Stacks Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) We will explore implementations based on array and linked list
  • 7. 7 class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack double top() const; // keep the stack unchanged // bool full(); // optional // void print() const; private: … }; Stack ADT update, ‘logical’ constructor/destructor, composition/decomposition ‘physical’ constructor/destructor Compare with List, see that it’s ‘operations’ that define the type! inspection, access
  • 8. 8 Using Stack int main(void) { Stack stack; stack.push(5.0); stack.push(6.5); stack.push(-3.0); stack.push(-8.0); stack.print(); cout << "Top: " << stack.top() << endl; stack.pop(); cout << "Top: " << stack.top() << endl; while (!stack.empty()) stack.pop(); stack.print(); return 0; } result
  • 9. 9 struct Node{ public: double data; Node* next; }; class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack bool full(); // unnecessary for linked lists double top() const; // keep the stack unchanged void print() const; private: Node* top; }; Stack using linked lists
  • 10. 10 void List::addHead(int newdata){ Nodeptr newPtr = new Node; newPtr->data = newdata; newPtr->next = head; head = newPtr; } void Stack::push(double x){ Node* newPtr = new Node; newPtr->data = x; newPtr->next = top; top = newPtr; } From ‘addHead’ to ‘push’ Push (addHead), Pop (deleteHead)
  • 11. 11 Implementation based on ‘existing’ linked lists Optional to learn  Good to see that we may ‘re-use’ linked lists
  • 12. 12 Now let’s implement a stack based on a linked list To make the best out of the code of List, we implement Stack by inheriting List To let Stack access private member head, we make Stack as a friend of List class List { public: List() { head = NULL; } // constructor ~List(); // destructor bool empty() { return head == NULL; } Node* insertNode(int index, double x); int deleteNode(double x); int searchNode(double x); void printList(void); private: Node* head; friend class Stack; };
  • 13. 13 class Stack : public List { public: Stack() {} ~Stack() {} double top() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else return head->data; } void push(const double x) { InsertNode(0, x); } double pop() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else { double val = head->data; DeleteNode(val); return val; } } void printStack() { printList(); } }; Note: the stack implementation based on a linked list will never be full. from List
  • 14. 14 Stack using arrays class Stack { public: Stack(int size = 10); // constructor ~Stack() { delete [] values; } // destructor bool empty() { return top == -1; } void push(const double x); double pop(); bool full() { return top == maxTop; } double top(); void print(); private: int maxTop; // max stack size = size - 1 int top; // current top of stack double* values; // element array };
  • 15. 15 Attributes of Stack maxTop: the max size of stack top: the index of the top element of stack values: point to an array which stores elements of stack Operations of Stack empty: return true if stack is empty, return false otherwise full: return true if stack is full, return false otherwise top: return the element at the top of stack push: add an element to the top of stack pop: delete the element at the top of stack print: print all the data in the stack
  • 16. 16 Allocate a stack array of size. By default, size = 10. Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e. size – 1. Stack::Stack(int size /*= 10*/) { values = new double[size]; top = -1; maxTop = size - 1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization. Stack constructor
  • 17. 17 void push(const double x); Push an element onto the stack Note top always represents the index of the top element. After pushing an element, increment top. void Stack::push(const double x) { if (full()) // if stack is full, print error cout << "Error: the stack is full." << endl; else values[++top] = x; }
  • 18. 18 double pop() Pop and return the element at the top of the stack Don’t forgot to decrement top double Stack::pop() { if (empty()) { //if stack is empty, print error cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--]; } }
  • 19. 19 double top() Return the top element of the stack Unlike pop, this function does not remove the top element double Stack::top() { if (empty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top]; }
  • 20. 20 void print() Print all the elements void Stack::print() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "t|t" << values[i] << "t|" << endl; cout << "t|---------------|" << endl; }
  • 21. 21 Stack Application: Balancing Symbols To check that every right brace, bracket, and parentheses must correspond to its left counterpart e.g. [( )] is legal, but [( ] ) is illegal Algorithm (1) Make an empty stack. (2) Read characters until end of file i. If the character is an opening symbol, push it onto the stack ii. If it is a closing symbol, then if the stack is empty, report an error iii. Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3) At end of file, if the stack is not empty, report an error
  • 22. 22 Stack Application: function calls and recursion Take the example of factorial! And run it. #include <iostream> using namespace std; int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ int number; cout << "Enter a positive integer : " << endl;; cin >> number; cout << fac(number) << endl; }
  • 23. 23 Assume the number typed is 3. fac(3): has the final returned value 6 3<=1 ? No. product3 = 3*fac(2) product3=3*2=6, return 6, fac(2): 2<=1 ? No. product2 = 2*fac(1) product2=2*1=2, return 2, fac(1): 1<=1 ? Yes. return 1 Tracing the program …
  • 24. 24 fac(3) prod3=3*fac(2) prod2=2*fac(1)fac(2) fac(1) prod1=1 Call is to ‘push’ and return is to ‘pop’! top
  • 25. 25 Array versus linked list implementations push, pop, top are all constant-time operations in both array and linked list implementation For array implementation, the operations are performed in very fast constant time
  • 26. 26 Queue Overview Queue ADT Basic operations of queue Enqueuing, dequeuing etc. Implementation of queue Linked list Array
  • 27. 27 Queue A queue is also a list. However, insertion is done at one end, while deletion is performed at the other end. It is “First In, First Out (FIFO)” order. Like customers standing in a check-out line in a store, the first customer in is the first customer served.
  • 28. 28 Enqueue and Dequeue Primary queue operations: Enqueue and Dequeue Like check-out lines in a store, a queue has a front and a rear. Enqueue – insert an element at the rear of the queue Dequeue – remove an element from the front of the queue Insert (Enqueue) Remove (Dequeue) rearfront
  • 29. 29 Implementation of Queue Just as stacks can be implemented as arrays or linked lists, so with queues. Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks
  • 30. 30 class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); void print(void); // bool full(); // optional private: … }; Queue ADT ‘physical’ constructor/destructor ‘logical’ constructor/destructor
  • 31. 31 Using Queueint main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.print(); queue.enqueue(7); queue.print(); return 0; }
  • 32. 32 Struct Node { double data; Node* next; } class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); // bool full(); // optional void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements }; Queue using linked lists
  • 33. 33 class Queue { public: Queue() { // constructor front = rear = NULL; counter = 0; } ~Queue() { // destructor double value; while (!empty()) dequeue(value); } bool empty() { if (counter) return false; else return true; } void enqueue(double x); double dequeue(); // bool full() {return false;}; void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements, not compulsary }; Implementation of some online member functions …
  • 34. 34 Enqueue (addEnd) void Queue::enqueue(double x) { Node* newNode = new Node; newNode->data = x; newNode->next = NULL; if (empty()) { front = newNode; } else { rear->next = newNode; } rear = newNode; counter++; } 8 rear rear newNode 5 58
  • 35. 35 Dequeue (deleteHead) double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { x = front->data; Node* nextNode = front->next; delete front; front = nextNode; counter--; } return x; } front 583 8 5 front
  • 36. 36 Printing all the elements void Queue::print() { cout << "front -->"; Node* currNode = front; for (int i = 0; i < counter; i++) { if (i == 0) cout << "t"; else cout << "tt"; cout << currNode->data; if (i != counter - 1) cout << endl; else cout << "t<-- rear" << endl; currNode = currNode->next; } }
  • 37. 37 Queue using Arrays There are several different algorithms to implement Enqueue and Dequeue Naïve way When enqueuing, the front index is always fixed and the rear index moves forward in the array. front rear Enqueue(3) 3 front rear Enqueue(6) 3 6 front rear Enqueue(9) 3 6 9
  • 38. 38 Naïve way (cont’d) When dequeuing, the front index is fixed, and the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) Dequeue() front rear 6 9 Dequeue() Dequeue() front rear 9 rear = -1 front
  • 39. 39 A better way When enqueued, the rear index moves forward. When dequeued, the front index also moves forward by one element XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) (front) The problem here is that the rear index cannot move beyond the last element in the array.
  • 40. 40 Using Circular Arrays Using a circular array When an element moves past the end of a circular array, it wraps around to the beginning, e.g. OOOOO7963  4OOOO7963 (after Enqueue(4)) How to detect an empty or full queue, using a circular array algorithm? Use a counter of the number of elements in the queue.
  • 41. 41 class Queue { public: Queue(int size = 10); // constructor Queue(Queue& queue); // not necessary! ~Queue() { delete [] values; } // destructor bool empty(void); void enqueue(double x); // or bool enqueue(); double dequeue(); bool full(); void print(void); private: int front; // front index int rear; // rear index int counter; // number of elements int maxSize; // size of array queue double* values; // element array }; full() is not essential, can be embedded
  • 42. 42 Attributes of Queue front/rear: front/rear index counter: number of elements in the queue maxSize: capacity of the queue values: point to an array which stores elements of the queue Operations of Queue empty: return true if queue is empty, return false otherwise full: return true if queue is full, return false otherwise enqueue: add an element to the rear of queue dequeue: delete the element at the front of queue print: print all the data
  • 43. 43 Queue constructor Queue(int size = 10) Allocate a queue array of size. By default, size = 10. front is set to 0, pointing to the first element of the array rear is set to -1. The queue is empty initially. Queue::Queue(int size /* = 10 */) { values = new double[size]; maxSize = size; front = 0; rear = -1; counter = 0; }
  • 44. 44 Empty & Full Since we keep track of the number of elements that are actually in the queue: counter, it is easy to check if the queue is empty or full. bool Queue::empty() { if (counter==0) return true; else return false; } bool Queue::full() { if (counter < maxSize) return false; else return true; }
  • 45. 45 Enqueue void Queue::enqueue(double x) { if (full()) { cout << "Error: the queue is full." << endl; exit(1); // return false; } else { // calculate the new rear position (circular) rear = (rear + 1) % maxSize; // insert new item values[rear] = x; // update counter counter++; // return true; } } Or ‘bool’ if you want
  • 46. 46 Dequeue double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { // retrieve the front item x = values[front]; // move front front = (front + 1) % maxSize; // update counter counter--; // return true; } return x; }
  • 47. 47 Printing the elements void Queue::print() { cout << "front -->"; for (int i = 0; i < counter; i++) { if (i == 0) cout << "t"; else cout << "tt"; cout << values[(front + i) % maxSize]; if (i != counter - 1) cout << endl; else cout << "t<-- rear" << endl; } }
  • 48. 48 Using Queueint main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.print(); queue.enqueue(7); queue.print(); return 0; }
  • 49. 49 Results Queue implemented using linked list will be never full! based on array based on linked list
  • 50. 50 Queue applications When jobs are sent to a printer, in order of arrival, a queue. Customers at ticket counters …