SlideShare ist ein Scribd-Unternehmen logo
1 von 76
Stacks and Queues
1 Introduction to the Stack ADT
• A stack is a data structure that stores and
retrieves items in a last-in-first-out (LIFO)
manner.
Applications of Stacks
• Computer systems use stacks during a
program’s execution to store function return
addresses, local variables, etc.
• Some calculators use stacks for performing
mathematical operations.
Static and Dynamic Stacks
• Static Stacks
– Fixed size
– Can be implemented with an array
• Dynamic Stacks
– Grow in size as needed
– Can be implemented with a linked list
Stack Operations
• Push
– causes a value to be stored in (pushed onto) the
stack
• Pop
– retrieves and removes a value from the stack
The Push Operation
• Suppose we have an empty integer stack
that is capable of holding a maximum of
three values. With that stack we execute the
following push operations.
push(5);
push(10);
push(15);
The Push Operation
The state of the stack after each of the push operations:
The Pop Operation
• Now, suppose we execute three consecutive
pop operations on the same stack:
Other Stack Operations
• isFull: A Boolean operation needed for
static stacks. Returns true if the stack is full.
Otherwise, returns false.
• isEmpty: A Boolean operation needed for
all stacks. Returns true if the stack is empty.
Otherwise, returns false.
The IntStack Class
• Table 1: Member Variables
Member Variable Description
stackArray stackArray A pointer to int. When the constructor is
executed, it uses
stackArray to dynamically allocate an array for storage.
stackSize An integer that holds the size of the stack.
top An integer that is used to mark the top of the stack.
The IntStack Class
• Table 2: Member Functions
Member Function Description
stackArray Constructor The class constructor accepts an integer
argument, which specifies the
size of the stack. An integer array of this size is dynamically
allocated, and assigned to stackArray. Also, the variable top is
initialized to –1.
push The push function accepts an integer argument, which is pushed onto
the top of the stack.
pop The pop function uses an integer reference parameter. The value at
the top of the stack is removed, and copied into the reference
parameter.
The IntStack Class
• Table 2: Member Functions (continued)
Member Function Description
stackArray isFull Returns true if the stack is full and false
otherwise. The stack is
full when top is equal to stackSize – 1.
isEmpty Returns true if the stack is empty, and false otherwise. The stack
is empty when top is set to –1.
Contents of IntStack.h
#ifndef INTSTACK_H
#define INTSTACK_H
class IntStack
{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int);
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
};
#endif
Contents of IntStack.cpp
#include <iostream.h>
#include "intstack.h“
//*******************
// Constructor *
//*******************
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
Contents of IntStack.cpp
//*************************************************
// Member function push pushes the argument onto *
// the stack. *
//*************************************************
void IntStack::push(int num)
{
if (isFull())
{
cout << "The stack is full.n";
}
else
{
top++;
stackArray[top] = num;
}
}
Contents of IntStack.cpp
//****************************************************
// Member function pop pops the value at the top *
// of the stack off, and copies it into the variable *
// passed as an argument. *
//****************************************************
void IntStack::pop(int &num)
{
if (isEmpty())
{
cout << "The stack is empty.n";
}
else
{
num = stackArray[top];
top--;
}
}
Contents of IntStack.cpp
//***************************************************
// Member function isFull returns true if the stack *
// is full, or false otherwise. *
//***************************************************
bool IntStack::isFull(void)
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
Contents of IntStack.cpp
//****************************************************
// Member funciton isEmpty returns true if the stack *
// is empty, or false otherwise. *
//****************************************************
bool IntStack::isEmpty(void)
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
Program 1
// This program demonstrates the IntStack class.
#include <iostream.h>
#include "intstack.h“
void main(void)
{
IntStack stack(5);
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
cout << "Pushing 20n";
stack.push(20);
cout << "Pushing 25n";
stack.push(25);
Program 1 (continued)
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
}
Program Output
Pushing 5
Pushing 10
Pushing 15
Pushing 20
Pushing 25
Popping...
25
20
15
10
5
Program 1 (continued)
About Program 1
• In the program, the constructor is called
with the argument 5. This sets up the
member variables as shown in Figure 4.
Since top is set to –1, the stack is empty
About Program 1
• Figure 5 shows the state of the member
variables after the push function is called
the first time (with 5 as its argument). The
top of the stack is now at element 0.
About Program 1
• Figure 6 shows the state of the member
variables after all five calls to the push
function. Now the top of the stack is at
element 4, and the stack is full.
About Program 1
• Notice that the pop function uses a
reference parameter, num. The value that is
popped off the stack is copied into num so it
can be used later in the program. Figure 7
(on the next slide) depicts the state of the
class members, and the num parameter, just
after the first value is popped off the stack.
About Program 1
Implementing Other Stack
Operations
• The MathStack class demonstrates
functions for stack-based arithmetic.
2 Dynamic Stacks
• A dynamic stack is built on a linked list instead of
an array.
• A linked list-based stack offers two advantages
over an array-based stack.
– No need to specify the starting size of the stack. A
dynamic stack simply starts as an empty linked list, and
then expands by one node each time a value is pushed.
– A dynamic stack will never be full, as long as the
system has enough free memory.
Contents of DynIntStack.h
class DynIntStack
{
private:
struct StackNode
{
int value;
StackNode *next;
};
StackNode *top;
public:
DynIntStack(void)
{ top = NULL; }
void push(int);
void pop(int &);
bool isEmpty(void);
};
Contents of DynIntStack.cpp
#include <iostream.h>
#include "dynintstack.h“
//************************************************
// Member function push pushes the argument onto *
// the stack. *
//************************************************
void DynIntStack::push(int num)
{
stackNode *newNode;
// Allocate a new node & store Num
newNode = new stackNode;
newNode->value = num;
Contents of DynIntStack.cpp
// If there are no nodes in the list
// make newNode the first node
if (isEmpty())
{
top = newNode;
newNode->next = NULL;
}
else // Otherwise, insert NewNode before top
{
newNode->next = top;
top = newNode;
}
}
//****************************************************
// Member function pop pops the value at the top *
// of the stack off, and copies it into the variable *
// passed as an argument. *
//****************************************************
Contents of DynIntStack.cpp
void DynIntStack::pop(int &num)
{
stackNode *temp;
if (isEmpty())
{
cout << "The stack is empty.n";
}
else // pop value off top of stack
{
num = top->value;
temp = top->next;
delete top;
top = temp;
}
}
Contents of DynIntStack.cpp
//****************************************************
// Member funciton isEmpty returns true if the stack *
// is empty, or false otherwise. *
//****************************************************
bool DynIntStack::isEmpty(void)
{
bool status;
if (!top)
status = true;
else
status = false;
return status;
}
Program 3
// This program demonstrates the dynamic stack
// class DynIntClass.
#include <iostream.h>
#include "dynintstack.h“
void main(void)
{
DynIntStack stack;
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
Program 3 (continued)
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
cout << "nAttempting to pop again... ";
stack.pop(catchVar);
}
Program Output
Pushing 5
Pushing 10
Pushing 15
Popping...
15
10
5
Attempting to pop again... The stack is empty.
3 The STL stack Container
• The STL stack container may be
implemented as a vector, a list, or a
deque.
• Because the stack container is used to
adapt these other containers, it is often
referred to as a container adapter.
3 The STL stack Container
• Here are examples of how to declare a stack
of ints, implemented as a vector, a
list, and a deque.
stack< int, vector<int> > iStack; // Vector stack
stack< int, list<int> > iStack; // List stack
stack< int > iStack; // Default – deque stack
Program 4
// This program demonstrates the STL stack
// container adapter.
#include <iostream.h>
#include <vector>
#include <stack>
using namespace std;
void main(void)
{
int x;
stack< int, vector<int> > iStack;
for (x = 2; x < 8; x += 2)
{
cout << "Pushing " << x << endl;
iStack.push(x);
}
Program 4 (continued)
cout << "The size of the stack is ";
cout << iStack.size() << endl;
for (x = 2; x < 8; x += 2)
{
cout << "Popping " << iStack.top() << endl;
iStack.pop();
}
}
Program Output
Pushing 2
Pushing 4
Pushing 6
The size of the stack is 3
Popping 6
Popping 4
Popping 2
4 Introduction to the Queue ADT
• Like a stack, a queue (pronounced "cue") is a data
structure that holds a sequence of elements.
• A queue, however, provides access to its elements
in first-in, first-out (FIFO) order.
• The elements in a queue are processed like
customers standing in a grocery check-out line:
the first customer in line is the first one served.
Example Applications of Queues
• In a multi-user system, a queue is used to hold
print jobs submitted by users , while the printer
services those jobs one at a time.
• Communications software also uses queues to
hold information received over networks and dial-
up connections. Sometimes information is
transmitted to a system faster than it can be
processed, so it is placed in a queue when it is
received.
Static and Dynamic Queues
• Just as stacks are implemented as arrays or
linked lists, so are queues.
• Dynamic queues offer the same advantages
over static queues that dynamic stacks offer
over static stacks.
Queue Operations
• Think of queues as having a front and a
rear. This is illustrated in Figure 8.
Queue Operations
• The two primary queue operations are
enqueuing and dequeuing.
• To enqueue means to insert an element at
the rear of a queue.
• To dequeue means to remove an element
from the front of a queue.
Queue Operations
• Suppose we have an empty static integer
queue that is capable of holding a maximum
of three values. With that queue we execute
the following enqueue operations.
Enqueue(3);
Enqueue(6);
Enqueue(9);
Queue Operations
• Figure 9 illustrates the state of the queue
after each of the enqueue operations.
Queue Operations
• Now let's see how dequeue operations are
performed. Figure 10 illustrates the state of the
queue after each of three consecutive dequeue
operations
Queue Operations
• When the last deqeue operation is
performed in the illustration, the queue is
empty. An empty queue can be signified by
setting both front and rear indices to –1.
Contents of IntQueue.h
class IntQueue
{
private:
int *queueArray;
int queueSize;
int front;
int rear;
int numItems;
public:
IntQueue(int);
~IntQueue(void);
void enqueue(int);
void dequeue(int &);
bool isEmpty(void);
bool isFull(void);
void clear(void);
};
Contents of IntQueue.cpp
#include <iostream.h>
#include "IntQueue.h“
//*************************
// Constructor *
//*************************
IntQueue::IntQueue(int s)
{
queueArray = new int[s];
queueSize = s;
front = 0;
rear = 0;
numItems = 0;
}
Contents of IntQueue.cpp
//*************************
// Destructor *
//*************************
IntQueue::~IntQueue(void)
{
delete [] queueArray;
}
Contents of IntQueue.cpp
//********************************************
// Function enqueue inserts the value in num *
// at the rear of the queue. *
//********************************************
void IntQueue::enqueue(int num)
{
if (isFull())
cout << "The queue is full.n";
else
{
// Calculate the new rear position
rear = (rear + 1) % queueSize;
// Insert new item
queueArray[rear] = num;
// Update item count
numItems++;
}
}
Contents of IntQueue.cpp
//*********************************************
// Function dequeue removes the value at the *
// front of the queue, and copies t into num. *
//*********************************************
void IntQueue::dequeue(int &num)
{
if (isEmpty())
cout << "The queue is empty.n";
else
{
// Move front
front = (front + 1) % queueSize;
// Retrieve the front item
num = queueArray[front];
// Update item count
numItems--;
}
}
Contents of IntQueue.cpp
//*********************************************
// Function isEmpty returns true if the queue *
// is empty, and false otherwise. *
//*********************************************
bool IntQueue::isEmpty(void)
{
bool status;
if (numItems)
status = false;
else
status = true;
return status;
}
Contents of IntQueue.cpp
//********************************************
// Function isFull returns true if the queue *
// is full, and false otherwise. *
//********************************************
bool IntQueue::isFull(void)
{
bool status;
if (numItems < queueSize)
status = false;
else
status = true;
return status;
}
Contents of IntQueue.cpp
//*******************************************
// Function clear resets the front and rear *
// indices, and sets numItems to 0. *
//*******************************************
void IntQueue::clear(void)
{
front = queueSize - 1;
rear = queueSize - 1;
numItems = 0;
}
Program 5
// This program demonstrates the IntQeue class
#include <iostream.h>
#include "intqueue.h“
void main(void)
{
IntQueue iQueue(5);
cout << "Enqueuing 5 items...n";
// Enqueue 5 items.
for (int x = 0; x < 5; x++)
iQueue.enqueue(x);
// Attempt to enqueue a 6th item.
cout << "Now attempting to enqueue again...n";
iQueue.enqueue(5);
Program 5 (continued)
// Deqeue and retrieve all items in the queue
cout << "The values in the queue were:n";
while (!iQueue.isEmpty())
{
int value;
iQueue.dequeue(value);
cout << value << endl;
}
}
Program Output
Enqueuing 5 items...
Now attempting to enqueue again...
The queue is full.
The values in the queue were:
0
5 Dynamic Queues
• A dynamic queue starts as an empty linked list.
• With the first enqueue operation, a node is added,
which is pointed to by front and rear pointers.
• As each new item is added to the queue, a new
node is added to the rear of the list, and the rear
pointer is updated to point to the new node.
• As each item is dequeued, the node pointed to by
the front pointer is deleted, and front is made
to point to the next node in the list.
Dynamic Queues
• Figure 14 shows the structure of a dynamic
queue.
Contents of DynIntQueue.h
class DynIntQueue
{
private:
struct QueueNode
{
int value;
QueueNode *next;
};
QueueNode *front;
QueueNode *rear;
int numItems;
public:
DynIntQueue(void);
~DynIntQueue(void);
void enqueue(int);
void dequeue(int &);
bool isEmpty(void);
void clear(void);
};
Contents of DynIntQueue.cpp
#include <iostream.h>
#include "dynintqueue.h“
//************************
// Constructor *
//************************
DynIntQueue::DynIntQueue(void)
{
front = NULL;
rear = NULL;
numItems = 0;
}
//************************
// Destructor *
//************************
DynIntQueue::~DynIntQueue(void)
{
clear();
}
Contents of DynIntQueue.cpp
//********************************************
// Function enqueue inserts the value in num *
// at the rear of the queue. *
//********************************************
void DynIntQueue::enqueue(int num)
{
QueueNode *newNode;
newNode = new QueueNode;
newNode->value = num;
newNode->next = NULL;
if (isEmpty())
{
front = newNode;
rear = newNode;
}
else
{
rear->next = newNode;
rear = newNode;
}
numItems++;
}
Contents of DynIntQueue.cpp
//**********************************************
// Function dequeue removes the value at the *
// front of the queue, and copies it into num. *
//**********************************************
void DynIntQueue::dequeue(int &num)
{
QueueNode *temp;
if (isEmpty())
cout << "The queue is empty.n";
else
{
num = front->value;
temp = front->next;
delete front;
front = temp;
numItems--;
}
}
Contents of DynIntQueue.cpp
//*********************************************
// Function isEmpty returns true if the queue *
// is empty, and false otherwise. *
//*********************************************
bool DynIntQueue::isEmpty(void)
{
bool status;
if (numItems)
status = false;
else
status = true;
return status;
}
Contents of DynIntQueue.cpp
//********************************************
// Function clear dequeues all the elements *
// in the queue. *
//********************************************
void DynIntQueue::clear(void)
{
int value; // Dummy variable for dequeue
while(!isEmpty())
dequeue(value);
}
Program 6
// This program demonstrates the DynIntQeue class
#include <iostream.h>
#include "dynintqueue.h“
void main(void)
{
DynIntQueue iQueue;
cout << "Enqueuing 5 items...n";
// Enqueue 5 items.
for (int x = 0; x < 5; x++)
iQueue.enqueue(x);
// Deqeue and retrieve all items in the queue
cout << "The values in the queue were:n";
while (!iQueue.isEmpty())
{
int value;
iQueue.dequeue(value);
cout << value << endl;
}
}
Program 6 (continued)
Program Ouput
Enqueuing 5 items...
The values in the queue were:
0
1
2
3
4
The STL deque and queue
Containers
• A deque (pronounced "deck" or "deek") is
a double-ended queue. It similar to a
vector, but allows efficient access to
values at both the front and the rear.
• The queue ADT is like the the stack
ADT: it is actually a container adapter.
The deque Container
• Programs that use the deque ADT must
include the deque header file.
• The push_back, pop_front, and
front member functions are used.
Program 7
// This program demonstrates the STL deque
// container.
#include <iostream.h>
#include <deque>
using namespace std;
void main(void)
{
int x;
deque<int> iDeque;
cout << "I will now enqueue items...n";
for (x = 2; x < 8; x += 2)
{
cout << "Pushing " << x << endl;
iDeque.push_back(x);
}
cout << "I will now dequeue items...n";
for (x = 2; x < 8; x += 2)
{
cout << "Popping " << iDeque.front() << endl;
iDeque.pop_front();
}
}
Program 7 (continued)
Program Output
I will now enqueue items...
Pushing 2
Pushing 4
Pushing 6
I will now dequeue items...
Popping 2
Popping 4
Popping 6
The queue Container Adapter
• The queue container adapter can be built
upon vectors, lists, or deques.
• By default, it uses deque as its base.
The queue Container Adapter
• The queue insertion and removal operations are
the same as those supported by the stack ADT:
push, pop, and top.
• The queue version of push always inserts an
element at the rear of the queue.
• The queue version of pop always removes an
element from the structure's front.
• The top function returns the value of the element
at the front of the queue.
Program 8
// This program demonstrates the STL queue
// container adapter.
#include <iostream.h>
#include <queue>
using namespace std;
void main(void)
{
int x;
queue<int> iQueue;
cout << "I will now enqueue items...n";
for (x = 2; x < 8; x += 2)
{
cout << "Pushing " << x << endl;
iQueue.push(x);
}
cout << "I will now dequeue items...n";
for (x = 2; x < 8; x += 2)
{
cout << "Popping " << iQueue.front() << endl;
iQueue.pop();
}
}
Program 8 (continued)
Program Output
I will now enqueue items...
Pushing 2
Pushing 4
Pushing 6
I will now dequeue items...
Popping 2
Popping 4
Popping 6

Weitere ähnliche Inhalte

Was ist angesagt?

Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Saket Pathak
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxDEEPAK948083
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationZakaria Hossain
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)Sangharsh agarwal
 
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)Darshankumar Prajapati
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQLPooja Dixit
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiersSrinivas Reddy
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONArun Sial
 

Was ist angesagt? (20)

Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
 
Burp suite
Burp suiteBurp suite
Burp suite
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
Different types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with AnimationDifferent types of Shoring Algorithms with Animation
Different types of Shoring Algorithms with Animation
 
Templates
TemplatesTemplates
Templates
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)
Multiple Flat Files(CSV) to Target Table in ODI12c(12.2.1.0.0)
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 

Andere mochten auch

Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...Ariel Carrion
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queuesRamzi Alqrainy
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in CKasun Ranga Wijeweera
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manualSANTOSH RATH
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesLuis Goldster
 
Data structure-questions
Data structure-questionsData structure-questions
Data structure-questionsShekhar Chander
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna universitysangeethajames07
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues iiTech_MX
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applicationsJsaddam Hussain
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 

Andere mochten auch (16)

Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in C
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Data structure-questions
Data structure-questionsData structure-questions
Data structure-questions
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna university
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
deque and it applications
deque and it applicationsdeque and it applications
deque and it applications
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues ii
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 

Ă„hnlich wie Stacks and queue

My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
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
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++Vineeta Garg
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
104332 sri vidhya eng notes
104332 sri vidhya eng notes104332 sri vidhya eng notes
104332 sri vidhya eng notesKrishnakumar Btech
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue Apurbo Datta
 
@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
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 
Ds
DsDs
DsAcad
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Muhammad Hammad Waseem
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 

Ă„hnlich wie Stacks and queue (20)

My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Algo>Stacks
Algo>StacksAlgo>Stacks
Algo>Stacks
 
Stacks
StacksStacks
Stacks
 
04 stacks
04 stacks04 stacks
04 stacks
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
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
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
104332 sri vidhya eng notes
104332 sri vidhya eng notes104332 sri vidhya eng notes
104332 sri vidhya eng notes
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Oop 1
Oop 1Oop 1
Oop 1
 
Stack and Queue
Stack and Queue Stack 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
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
Stack
StackStack
Stack
 
Ds
DsDs
Ds
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 

Mehr von Amit Vats

Mi 103 mi 103 quiz 2
Mi 103 mi 103 quiz 2Mi 103 mi 103 quiz 2
Mi 103 mi 103 quiz 2Amit Vats
 
Mi 103 mi 103 quiz 2 (1)
Mi 103 mi 103 quiz 2 (1)Mi 103 mi 103 quiz 2 (1)
Mi 103 mi 103 quiz 2 (1)Amit Vats
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked listAmit Vats
 
Binary trees
Binary treesBinary trees
Binary treesAmit Vats
 
Handling
HandlingHandling
HandlingAmit Vats
 

Mehr von Amit Vats (6)

Mi 103 mi 103 quiz 2
Mi 103 mi 103 quiz 2Mi 103 mi 103 quiz 2
Mi 103 mi 103 quiz 2
 
Mi 103 mi 103 quiz 2 (1)
Mi 103 mi 103 quiz 2 (1)Mi 103 mi 103 quiz 2 (1)
Mi 103 mi 103 quiz 2 (1)
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
 
List
ListList
List
 
Binary trees
Binary treesBinary trees
Binary trees
 
Handling
HandlingHandling
Handling
 

KĂĽrzlich hochgeladen

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 

KĂĽrzlich hochgeladen (20)

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 

Stacks and queue

  • 2. 1 Introduction to the Stack ADT • A stack is a data structure that stores and retrieves items in a last-in-first-out (LIFO) manner.
  • 3. Applications of Stacks • Computer systems use stacks during a program’s execution to store function return addresses, local variables, etc. • Some calculators use stacks for performing mathematical operations.
  • 4. Static and Dynamic Stacks • Static Stacks – Fixed size – Can be implemented with an array • Dynamic Stacks – Grow in size as needed – Can be implemented with a linked list
  • 5. Stack Operations • Push – causes a value to be stored in (pushed onto) the stack • Pop – retrieves and removes a value from the stack
  • 6. The Push Operation • Suppose we have an empty integer stack that is capable of holding a maximum of three values. With that stack we execute the following push operations. push(5); push(10); push(15);
  • 7. The Push Operation The state of the stack after each of the push operations:
  • 8. The Pop Operation • Now, suppose we execute three consecutive pop operations on the same stack:
  • 9. Other Stack Operations • isFull: A Boolean operation needed for static stacks. Returns true if the stack is full. Otherwise, returns false. • isEmpty: A Boolean operation needed for all stacks. Returns true if the stack is empty. Otherwise, returns false.
  • 10. The IntStack Class • Table 1: Member Variables Member Variable Description stackArray stackArray A pointer to int. When the constructor is executed, it uses stackArray to dynamically allocate an array for storage. stackSize An integer that holds the size of the stack. top An integer that is used to mark the top of the stack.
  • 11. The IntStack Class • Table 2: Member Functions Member Function Description stackArray Constructor The class constructor accepts an integer argument, which specifies the size of the stack. An integer array of this size is dynamically allocated, and assigned to stackArray. Also, the variable top is initialized to –1. push The push function accepts an integer argument, which is pushed onto the top of the stack. pop The pop function uses an integer reference parameter. The value at the top of the stack is removed, and copied into the reference parameter.
  • 12. The IntStack Class • Table 2: Member Functions (continued) Member Function Description stackArray isFull Returns true if the stack is full and false otherwise. The stack is full when top is equal to stackSize – 1. isEmpty Returns true if the stack is empty, and false otherwise. The stack is empty when top is set to –1.
  • 13. Contents of IntStack.h #ifndef INTSTACK_H #define INTSTACK_H class IntStack { private: int *stackArray; int stackSize; int top; public: IntStack(int); void push(int); void pop(int &); bool isFull(void); bool isEmpty(void); }; #endif
  • 14. Contents of IntStack.cpp #include <iostream.h> #include "intstack.h“ //******************* // Constructor * //******************* IntStack::IntStack(int size) { stackArray = new int[size]; stackSize = size; top = -1; }
  • 15. Contents of IntStack.cpp //************************************************* // Member function push pushes the argument onto * // the stack. * //************************************************* void IntStack::push(int num) { if (isFull()) { cout << "The stack is full.n"; } else { top++; stackArray[top] = num; } }
  • 16. Contents of IntStack.cpp //**************************************************** // Member function pop pops the value at the top * // of the stack off, and copies it into the variable * // passed as an argument. * //**************************************************** void IntStack::pop(int &num) { if (isEmpty()) { cout << "The stack is empty.n"; } else { num = stackArray[top]; top--; } }
  • 17. Contents of IntStack.cpp //*************************************************** // Member function isFull returns true if the stack * // is full, or false otherwise. * //*************************************************** bool IntStack::isFull(void) { bool status; if (top == stackSize - 1) status = true; else status = false; return status; }
  • 18. Contents of IntStack.cpp //**************************************************** // Member funciton isEmpty returns true if the stack * // is empty, or false otherwise. * //**************************************************** bool IntStack::isEmpty(void) { bool status; if (top == -1) status = true; else status = false; return status; }
  • 19. Program 1 // This program demonstrates the IntStack class. #include <iostream.h> #include "intstack.h“ void main(void) { IntStack stack(5); int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15); cout << "Pushing 20n"; stack.push(20); cout << "Pushing 25n"; stack.push(25);
  • 20. Program 1 (continued) cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; }
  • 21. Program Output Pushing 5 Pushing 10 Pushing 15 Pushing 20 Pushing 25 Popping... 25 20 15 10 5 Program 1 (continued)
  • 22. About Program 1 • In the program, the constructor is called with the argument 5. This sets up the member variables as shown in Figure 4. Since top is set to –1, the stack is empty
  • 23. About Program 1 • Figure 5 shows the state of the member variables after the push function is called the first time (with 5 as its argument). The top of the stack is now at element 0.
  • 24. About Program 1 • Figure 6 shows the state of the member variables after all five calls to the push function. Now the top of the stack is at element 4, and the stack is full.
  • 25. About Program 1 • Notice that the pop function uses a reference parameter, num. The value that is popped off the stack is copied into num so it can be used later in the program. Figure 7 (on the next slide) depicts the state of the class members, and the num parameter, just after the first value is popped off the stack.
  • 27. Implementing Other Stack Operations • The MathStack class demonstrates functions for stack-based arithmetic.
  • 28. 2 Dynamic Stacks • A dynamic stack is built on a linked list instead of an array. • A linked list-based stack offers two advantages over an array-based stack. – No need to specify the starting size of the stack. A dynamic stack simply starts as an empty linked list, and then expands by one node each time a value is pushed. – A dynamic stack will never be full, as long as the system has enough free memory.
  • 29. Contents of DynIntStack.h class DynIntStack { private: struct StackNode { int value; StackNode *next; }; StackNode *top; public: DynIntStack(void) { top = NULL; } void push(int); void pop(int &); bool isEmpty(void); };
  • 30. Contents of DynIntStack.cpp #include <iostream.h> #include "dynintstack.h“ //************************************************ // Member function push pushes the argument onto * // the stack. * //************************************************ void DynIntStack::push(int num) { stackNode *newNode; // Allocate a new node & store Num newNode = new stackNode; newNode->value = num;
  • 31. Contents of DynIntStack.cpp // If there are no nodes in the list // make newNode the first node if (isEmpty()) { top = newNode; newNode->next = NULL; } else // Otherwise, insert NewNode before top { newNode->next = top; top = newNode; } } //**************************************************** // Member function pop pops the value at the top * // of the stack off, and copies it into the variable * // passed as an argument. * //****************************************************
  • 32. Contents of DynIntStack.cpp void DynIntStack::pop(int &num) { stackNode *temp; if (isEmpty()) { cout << "The stack is empty.n"; } else // pop value off top of stack { num = top->value; temp = top->next; delete top; top = temp; } }
  • 33. Contents of DynIntStack.cpp //**************************************************** // Member funciton isEmpty returns true if the stack * // is empty, or false otherwise. * //**************************************************** bool DynIntStack::isEmpty(void) { bool status; if (!top) status = true; else status = false; return status; }
  • 34. Program 3 // This program demonstrates the dynamic stack // class DynIntClass. #include <iostream.h> #include "dynintstack.h“ void main(void) { DynIntStack stack; int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15);
  • 35. Program 3 (continued) cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; cout << "nAttempting to pop again... "; stack.pop(catchVar); } Program Output Pushing 5 Pushing 10 Pushing 15 Popping... 15 10 5 Attempting to pop again... The stack is empty.
  • 36. 3 The STL stack Container • The STL stack container may be implemented as a vector, a list, or a deque. • Because the stack container is used to adapt these other containers, it is often referred to as a container adapter.
  • 37. 3 The STL stack Container • Here are examples of how to declare a stack of ints, implemented as a vector, a list, and a deque. stack< int, vector<int> > iStack; // Vector stack stack< int, list<int> > iStack; // List stack stack< int > iStack; // Default – deque stack
  • 38. Program 4 // This program demonstrates the STL stack // container adapter. #include <iostream.h> #include <vector> #include <stack> using namespace std; void main(void) { int x; stack< int, vector<int> > iStack; for (x = 2; x < 8; x += 2) { cout << "Pushing " << x << endl; iStack.push(x); }
  • 39. Program 4 (continued) cout << "The size of the stack is "; cout << iStack.size() << endl; for (x = 2; x < 8; x += 2) { cout << "Popping " << iStack.top() << endl; iStack.pop(); } } Program Output Pushing 2 Pushing 4 Pushing 6 The size of the stack is 3 Popping 6 Popping 4 Popping 2
  • 40. 4 Introduction to the Queue ADT • Like a stack, a queue (pronounced "cue") is a data structure that holds a sequence of elements. • A queue, however, provides access to its elements in first-in, first-out (FIFO) order. • The elements in a queue are processed like customers standing in a grocery check-out line: the first customer in line is the first one served.
  • 41. Example Applications of Queues • In a multi-user system, a queue is used to hold print jobs submitted by users , while the printer services those jobs one at a time. • Communications software also uses queues to hold information received over networks and dial- up connections. Sometimes information is transmitted to a system faster than it can be processed, so it is placed in a queue when it is received.
  • 42. Static and Dynamic Queues • Just as stacks are implemented as arrays or linked lists, so are queues. • Dynamic queues offer the same advantages over static queues that dynamic stacks offer over static stacks.
  • 43. Queue Operations • Think of queues as having a front and a rear. This is illustrated in Figure 8.
  • 44. Queue Operations • The two primary queue operations are enqueuing and dequeuing. • To enqueue means to insert an element at the rear of a queue. • To dequeue means to remove an element from the front of a queue.
  • 45. Queue Operations • Suppose we have an empty static integer queue that is capable of holding a maximum of three values. With that queue we execute the following enqueue operations. Enqueue(3); Enqueue(6); Enqueue(9);
  • 46. Queue Operations • Figure 9 illustrates the state of the queue after each of the enqueue operations.
  • 47. Queue Operations • Now let's see how dequeue operations are performed. Figure 10 illustrates the state of the queue after each of three consecutive dequeue operations
  • 48. Queue Operations • When the last deqeue operation is performed in the illustration, the queue is empty. An empty queue can be signified by setting both front and rear indices to –1.
  • 49. Contents of IntQueue.h class IntQueue { private: int *queueArray; int queueSize; int front; int rear; int numItems; public: IntQueue(int); ~IntQueue(void); void enqueue(int); void dequeue(int &); bool isEmpty(void); bool isFull(void); void clear(void); };
  • 50. Contents of IntQueue.cpp #include <iostream.h> #include "IntQueue.h“ //************************* // Constructor * //************************* IntQueue::IntQueue(int s) { queueArray = new int[s]; queueSize = s; front = 0; rear = 0; numItems = 0; }
  • 51. Contents of IntQueue.cpp //************************* // Destructor * //************************* IntQueue::~IntQueue(void) { delete [] queueArray; }
  • 52. Contents of IntQueue.cpp //******************************************** // Function enqueue inserts the value in num * // at the rear of the queue. * //******************************************** void IntQueue::enqueue(int num) { if (isFull()) cout << "The queue is full.n"; else { // Calculate the new rear position rear = (rear + 1) % queueSize; // Insert new item queueArray[rear] = num; // Update item count numItems++; } }
  • 53. Contents of IntQueue.cpp //********************************************* // Function dequeue removes the value at the * // front of the queue, and copies t into num. * //********************************************* void IntQueue::dequeue(int &num) { if (isEmpty()) cout << "The queue is empty.n"; else { // Move front front = (front + 1) % queueSize; // Retrieve the front item num = queueArray[front]; // Update item count numItems--; } }
  • 54. Contents of IntQueue.cpp //********************************************* // Function isEmpty returns true if the queue * // is empty, and false otherwise. * //********************************************* bool IntQueue::isEmpty(void) { bool status; if (numItems) status = false; else status = true; return status; }
  • 55. Contents of IntQueue.cpp //******************************************** // Function isFull returns true if the queue * // is full, and false otherwise. * //******************************************** bool IntQueue::isFull(void) { bool status; if (numItems < queueSize) status = false; else status = true; return status; }
  • 56. Contents of IntQueue.cpp //******************************************* // Function clear resets the front and rear * // indices, and sets numItems to 0. * //******************************************* void IntQueue::clear(void) { front = queueSize - 1; rear = queueSize - 1; numItems = 0; }
  • 57. Program 5 // This program demonstrates the IntQeue class #include <iostream.h> #include "intqueue.h“ void main(void) { IntQueue iQueue(5); cout << "Enqueuing 5 items...n"; // Enqueue 5 items. for (int x = 0; x < 5; x++) iQueue.enqueue(x); // Attempt to enqueue a 6th item. cout << "Now attempting to enqueue again...n"; iQueue.enqueue(5);
  • 58. Program 5 (continued) // Deqeue and retrieve all items in the queue cout << "The values in the queue were:n"; while (!iQueue.isEmpty()) { int value; iQueue.dequeue(value); cout << value << endl; } } Program Output Enqueuing 5 items... Now attempting to enqueue again... The queue is full. The values in the queue were: 0
  • 59. 5 Dynamic Queues • A dynamic queue starts as an empty linked list. • With the first enqueue operation, a node is added, which is pointed to by front and rear pointers. • As each new item is added to the queue, a new node is added to the rear of the list, and the rear pointer is updated to point to the new node. • As each item is dequeued, the node pointed to by the front pointer is deleted, and front is made to point to the next node in the list.
  • 60. Dynamic Queues • Figure 14 shows the structure of a dynamic queue.
  • 61. Contents of DynIntQueue.h class DynIntQueue { private: struct QueueNode { int value; QueueNode *next; }; QueueNode *front; QueueNode *rear; int numItems; public: DynIntQueue(void); ~DynIntQueue(void); void enqueue(int); void dequeue(int &); bool isEmpty(void); void clear(void); };
  • 62. Contents of DynIntQueue.cpp #include <iostream.h> #include "dynintqueue.h“ //************************ // Constructor * //************************ DynIntQueue::DynIntQueue(void) { front = NULL; rear = NULL; numItems = 0; } //************************ // Destructor * //************************ DynIntQueue::~DynIntQueue(void) { clear(); }
  • 63. Contents of DynIntQueue.cpp //******************************************** // Function enqueue inserts the value in num * // at the rear of the queue. * //******************************************** void DynIntQueue::enqueue(int num) { QueueNode *newNode; newNode = new QueueNode; newNode->value = num; newNode->next = NULL; if (isEmpty()) { front = newNode; rear = newNode; } else { rear->next = newNode; rear = newNode; } numItems++; }
  • 64. Contents of DynIntQueue.cpp //********************************************** // Function dequeue removes the value at the * // front of the queue, and copies it into num. * //********************************************** void DynIntQueue::dequeue(int &num) { QueueNode *temp; if (isEmpty()) cout << "The queue is empty.n"; else { num = front->value; temp = front->next; delete front; front = temp; numItems--; } }
  • 65. Contents of DynIntQueue.cpp //********************************************* // Function isEmpty returns true if the queue * // is empty, and false otherwise. * //********************************************* bool DynIntQueue::isEmpty(void) { bool status; if (numItems) status = false; else status = true; return status; }
  • 66. Contents of DynIntQueue.cpp //******************************************** // Function clear dequeues all the elements * // in the queue. * //******************************************** void DynIntQueue::clear(void) { int value; // Dummy variable for dequeue while(!isEmpty()) dequeue(value); }
  • 67. Program 6 // This program demonstrates the DynIntQeue class #include <iostream.h> #include "dynintqueue.h“ void main(void) { DynIntQueue iQueue; cout << "Enqueuing 5 items...n"; // Enqueue 5 items. for (int x = 0; x < 5; x++) iQueue.enqueue(x); // Deqeue and retrieve all items in the queue cout << "The values in the queue were:n"; while (!iQueue.isEmpty()) { int value; iQueue.dequeue(value); cout << value << endl; } }
  • 68. Program 6 (continued) Program Ouput Enqueuing 5 items... The values in the queue were: 0 1 2 3 4
  • 69. The STL deque and queue Containers • A deque (pronounced "deck" or "deek") is a double-ended queue. It similar to a vector, but allows efficient access to values at both the front and the rear. • The queue ADT is like the the stack ADT: it is actually a container adapter.
  • 70. The deque Container • Programs that use the deque ADT must include the deque header file. • The push_back, pop_front, and front member functions are used.
  • 71. Program 7 // This program demonstrates the STL deque // container. #include <iostream.h> #include <deque> using namespace std; void main(void) { int x; deque<int> iDeque; cout << "I will now enqueue items...n"; for (x = 2; x < 8; x += 2) { cout << "Pushing " << x << endl; iDeque.push_back(x); } cout << "I will now dequeue items...n"; for (x = 2; x < 8; x += 2) { cout << "Popping " << iDeque.front() << endl; iDeque.pop_front(); } }
  • 72. Program 7 (continued) Program Output I will now enqueue items... Pushing 2 Pushing 4 Pushing 6 I will now dequeue items... Popping 2 Popping 4 Popping 6
  • 73. The queue Container Adapter • The queue container adapter can be built upon vectors, lists, or deques. • By default, it uses deque as its base.
  • 74. The queue Container Adapter • The queue insertion and removal operations are the same as those supported by the stack ADT: push, pop, and top. • The queue version of push always inserts an element at the rear of the queue. • The queue version of pop always removes an element from the structure's front. • The top function returns the value of the element at the front of the queue.
  • 75. Program 8 // This program demonstrates the STL queue // container adapter. #include <iostream.h> #include <queue> using namespace std; void main(void) { int x; queue<int> iQueue; cout << "I will now enqueue items...n"; for (x = 2; x < 8; x += 2) { cout << "Pushing " << x << endl; iQueue.push(x); } cout << "I will now dequeue items...n"; for (x = 2; x < 8; x += 2) { cout << "Popping " << iQueue.front() << endl; iQueue.pop(); } }
  • 76. Program 8 (continued) Program Output I will now enqueue items... Pushing 2 Pushing 4 Pushing 6 I will now dequeue items... Popping 2 Popping 4 Popping 6