Sei sulla pagina 1di 35

Queues

Chapter 8

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 1
Education, Inc. All rights reserved. 0-13-140909-3
Chapter Contents
8.1 Introduction to Queues
8.2 Designing and Building a Queue Class –
Array Based
8.3 Linked Queues
8.4 Application of Queues: Buffers and
Scheduling
8.5 Case Study: Center Simulation

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 2
Education, Inc. All rights reserved. 0-13-140909-3
Chapter Objectives
• To study a queue as an ADT
• Build a static-array-based implementation of
queues
• Build a dynamic-array-based implementation of
queues
• Show how queues are used in I/O buffers and
scheduling in a computer system
• (Optional) See how queues are used in simulations
of phenomena that involve waiting in lines

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 3
Education, Inc. All rights reserved. 0-13-140909-3
Introduction to Queues
• A queue is a waiting line – seen in daily life
– A line of people waiting for a bank teller
– A line of cars at a toll both
– "This is the captain, we're 5th in line for takeoff"
• What other kinds of queues can you think of

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 4
Education, Inc. All rights reserved. 0-13-140909-3
The Queue As an ADT
• A queue is a sequence of data elements
• In the sequence
– Items can be removed only at the front
– Items can be added only at the other end, the back
• Basic operations
– Construct a queue
– Check if empty
– Enqueue (add element to back)
– Front (retrieve value of element from front)
– Dequeue (remove element from front)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 5
Education, Inc. All rights reserved. 0-13-140909-3
Designing and Building a Queue
Class Array-Based
• Consider an array in which to store a queue

• Note additional variables needed


– myFront, myBack
• Picture a queue
object like this
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 6
Education, Inc. All rights reserved. 0-13-140909-3
Designing and Building a Queue
Class Array-Based
• Problems
– We quickly "walk off the end" of the array
• Possible solutions
– Shift array elements
– Use a circular queue

– Note that both empty


and full queue
gives myBack == myFront
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 7
Education, Inc. All rights reserved. 0-13-140909-3
Designing and Building a Queue
Class Array-Based
• Using a static array
– QUEUE_CAPACITY specified
– Enqueue increments myBack using mod
operator, checks for full queue
– Dequeue increments myFront using mod
operator, checks for empty queue.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 8
Education, Inc. All rights reserved. 0-13-140909-3
Using Dynamic Array to Store
Queue Elements
• Similar problems as with list and stack
– Fixed size array can be specified too large or too
small
• Dynamic array design allows sizing of array
for multiple situations
• Results in structure as shown
– myCapacity
determined
at run time
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 9
Education, Inc. All rights reserved. 0-13-140909-3
Linked Queues
• Even with dynamic allocation of queue size
– Array size is still fixed
– Cannot be adjusted during run of program
• Could use linked list to store queue elements
– Can grow and shrink to fit the situation
– No need for upper bound (myCapacity)

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 10
Education, Inc. All rights reserved. 0-13-140909-3
Circular Linked List
• Possible to treat the linked list as circular

– Last node points back to first node


– Alternatively keep pointer to last node rather
than first node

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 11
Education, Inc. All rights reserved. 0-13-140909-3
Application of Queues: Buffers and
Scheduling
• Important use of queues is I/O scheduling
– Use buffers in memory to improve program
execution

– Buffer arranged
in FIFO
structure

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 12
Education, Inc. All rights reserved. 0-13-140909-3
Application of Queues: Buffers and
Scheduling
• Also times when insertions, deletions must
be made from both ends
– Consider a scrolling
window on the screen
• This requires a double
ended queue
– Called a deque (pronounced "deck")
– Could also be considered a double ended stack
(or "dack")
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 13
Education, Inc. All rights reserved. 0-13-140909-3
Application of Queues: Buffers and
Scheduling
• Consider a keyboard buffer
– Acts as a queue
– But elements may be
removed from the back of
the queue with
backspace key
• A printer spool is a queue of print jobs

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 14
Education, Inc. All rights reserved. 0-13-140909-3
Application of Queues: Buffers and
Scheduling
• Queues used to
schedule tasks
within an operating
system

• Job moves from disk to ready queue

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 15
Education, Inc. All rights reserved. 0-13-140909-3
Application of Queues: Buffers and
Scheduling
• Ready queue may actually
be a priority queue … job may get to "cut the
line" based on its priority

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 16
Education, Inc. All rights reserved. 0-13-140909-3
Templates

Reference: Chapter 14, Object-Oriented Programming in C++, Robert Lafore


#include <iostream>
EX1: Template used for absolute value using namespace std;
//--------------------------------------------------------------
template <class T>
T abs(T n)
{
return (n < 0) ? -n : n;
}
//--------------------------------------------------------------
int main()
{
function

int int1 = 5;
int int2 = -6;
long lon1 = 70000L;
long lon2 = -80000L;
double dub1 = 9.95;
double dub2 = -10.15;
//calls instantiate functions
cout << "\nabs(" << int1 << ")=" << abs(int1); //abs(int)
cout << "\nabs(" << int2 << ")=" << abs(int2); //abs(int)
cout << "\nabs(" << lon1 << ")=" << abs(lon1); //abs(long)
cout << "\nabs(" << lon2 << ")=" << abs(lon2); //abs(long)
cout << "\nabs(" << dub1 << ")=" << abs(dub1);
//abs(double)
cout << "\nabs(" << dub2 << ")=" << abs(dub2);
//abs(double)
#include <iostream>
EX2/1: Template used for function that finds using namespace std;
//--------------------------------------------------------------
//function returns index number of item, or -1 if not found
template <class atype>
int find(atype* array, atype value, int size)
{
for(int j=0; j<size; j++)
if(array[j]==value)
number in array

return j;
return -1;
}
//--------------------------------------------------------------
char chrArr[] = {1, 3, 5, 9, 11, 13}; //array
char ch = 5; //value to find
int intArr[] = {1, 3, 5, 9, 11, 13};
int in = 6;
long lonArr[] = {1L, 3L, 5L, 9L, 11L, 13L};
long lo = 11L;
double dubArr[] = {1.0, 3.0, 5.0, 9.0, 11.0, 13.0};
double db = 4.0;
int main()
EX2/2: Template used for function that finds {
cout << "\n 5 in chrArray: index=" << find(chrArr, ch, 6);
cout << "\n 6 in intArray: index=" << find(intArr, in, 6);
cout << "\n11 in lonArray: index=" << find(lonArr, lo, 6);
cout << "\n 4 in dubArray: index=" << find(dubArr, db, 6);
cout << endl;
return 0;
}
number in array
EX3/1: Implements stack class as a template
#include <iostream>
using namespace std;
const int MAX = 100; //size of array
////////////////////////////////////////////////////////////////
template <class Type>
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{ top = -1; }
void push(Type var) //put number on stack
{ st[++top] = var; }
Type pop() //take number off stack
{ return st[top--]; }
};
EX3/2: Implements stack class as a template
int main()
{
Stack<float> s1; //s1 is object of class Stack<float>

s1.push(1111.1F); //push 3 floats, pop 3 floats


s1.push(2222.2F);
s1.push(3333.3F);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;

Stack<long> s2; //s2 is object of class Stack<long>

s2.push(123123123L); //push 3 longs, pop 3 longs


s2.push(234234234L);
s2.push(345345345L);
cout << "1: " << s2.pop() << endl;
cout << "2: " << s2.pop() << endl;
cout << "3: " << s2.pop() << endl;
return 0;
}
const int MAX = 100;
////////////////////////////////////////////////////////////////
template, member functions are defined template <class Type>
EX4/1: Implements stack class as a

class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
outside the class

public:
Stack(); //constructor
void push(Type var); //put number on stack
Type pop(); //take number off stack
};
////////////////////////////////////////////////////////////////
template<class Type>
Stack<Type>::Stack() //constructor
{
top = -1;
}
//--------------------------------------------------------------
template<class Type>
void Stack<Type>::push(Type var) //put number on stack
{
st[++top] = var;
}
template<class Type>
Type Stack<Type>::pop() //take number off stack
template, member functions are defined {
return st[top--];
EX4/2: Implements stack class as a

}
//--------------------------------------------------------------
int main()
{
Stack<float> s1; //s1 is object of class Stack<float>
outside the class

s1.push(1111.1F); //push 3 floats, pop 3 floats


s1.push(2222.2F);
s1.push(3333.3F);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;

Stack<long> s2; //s2 is object of class Stack<long>

s2.push(123123123L); //push 3 longs, pop 3 longs


s2.push(234234234L);
s2.push(345345345L);
cout << "1: " << s2.pop() << endl;
cout << "2: " << s2.pop() << endl;
cout << "3: " << s2.pop() << endl;
return 0;}
#include <iostream>
EX5/1: Implements linked list as a template using namespace std;
////////////////////////////////////////////////////////////////
template<class TYPE>
struct link
{
TYPE data; //data item
link* next; //pointer to next link
};
////////////////////////////////////////////////////////////////
template<class TYPE>
class linklist
{
private:
link<TYPE>* first; //pointer to first link
public:
linklist() //no-argument constructor
{ first = NULL; } //no first link
//note: destructor would be nice; not shown for simplicity
void additem(TYPE d); //add data item (one link)
void display(); //display all links
};
template<class TYPE>
EX5/2: Implements linked list as a template void linklist<TYPE>::additem(TYPE d)
{
link<TYPE>* newlink = new link<TYPE>; //make a new link
newlink->data = d; //give it data
newlink->next = first; //it points to next link
first = newlink; //now first points to this
}
//--------------------------------------------------------------
template<class TYPE>
void linklist<TYPE>::display()
{
link<TYPE>* current = first; //set ptr to first link
while( current != NULL ) //quit on last link
{
cout << endl << current->data; //print data
current = current->next; //move to next link
}
}
int main()
EX5/3: Implements linked list as a template {
linklist<double> ld; //ld is object of class linklist<double>

ld.additem(151.5); //add three doubles to list ld


ld.additem(262.6);
ld.additem(373.7);
ld.display(); //display entire list ld

linklist<char> lch; //lch is object of class linklist<char>

lch.additem('a'); //add three chars to list lch


lch.additem('b');
lch.additem('c');
lch.display(); //display entire list lch
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
EX17/1: Overloaded << and >> operators ////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0) //constructor (no args)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
friend istream& operator >> (istream& s, Distance& d);
friend ostream& operator << (ostream& s, Distance& d);
};
//--------------------------------------------------------------
istream& operator >> (istream& s, Distance& d) //get Distance
{ //from user
cout << "\nEnter feet: "; s >> d.feet; //using
cout << "Enter inches: "; s >> d.inches; //overloaded
return s; //>> operator
}
//--------------------------------------------------------------
ostream& operator << (ostream& s, Distance& d) //display
{ //Distance
s << d.feet << "\'-" << d.inches << '\"'; //using
return s; //overloaded
} //<< operator
int main()
{
EX17/2: Overloaded << and >> operators Distance dist1, dist2; //define Distances
Distance dist3(11, 6.25); //define, initialize dist3

cout << "\nEnter two Distance values:";


cin >> dist1 >> dist2; //get values from user
//display distances
cout << "\ndist1 = " << dist1 << "\ndist2 = " << dist2;
cout << "\ndist3 = " << dist3 << endl;
return 0;
}
class Distance //English Distance class
EX18/1: Overloaded << and >> operators {
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0) //constructor (no args)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
can work with files

{ }
friend istream& operator >> (istream& s, Distance& d);
friend ostream& operator << (ostream& s, Distance& d);
};
//--------------------------------------------------------------
istream& operator >> (istream& s, Distance& d) //get Distance
{ //from file or
char dummy; //for ('), (-), and (") //keyboard
//with
s >> d.feet >> dummy >> dummy >> d.inches >> dummy;
return s; //overloaded
} //>> operator
//--------------------------------------------------------------
ostream& operator << (ostream& s, Distance& d) //send Distance
{ //to file or
s << d.feet << "\'-" << d.inches << '\"'; //screen with
return s; //overloaded
}
int main()
EX18/2: Overloaded << and >> operators {
char ch;
Distance dist1;
ofstream ofile; //create and open
ofile.open("C:\\DIST.DAT"); //output stream

do {
cout << "\nEnter Distance: ";
can work with files

cin >> dist1; //get distance from user


ofile << dist1; //write it to output str
cout << "Do another (y/n)? ";
cin >> ch;
} while(ch != 'n');
ofile.close(); //close output stream

ifstream ifile; //create and open


ifile.open("C:\\DIST.DAT"); //input stream

cout << "\nContents of disk file is:\n";


while(true)
{
ifile >> dist1; //read dist from stream
if( ifile.eof() ) //quit on EOF
break;
cout << "Distance = " << dist1 <<endl; //display distance
}
return 0;
}
#include <iostream>
EX6/1: Implements linked list as a template,
demonstrates list used with employee class
using namespace std;
const int LEN = 80; //maximum length of

////////////////////////////////////////////////////////////////
class employee //employee class
{
private:
char name[LEN]; //employee name
unsigned long number; //employee number
public:
friend istream& operator >> (istream& s, employee& e);
friend ostream& operator << (ostream& s, employee& e);
};
//--------------------------------------------------------------
istream& operator >> (istream& s, employee& e)
{
cout << "\n Enter last name: "; cin >> e.name;
cout << " Enter number: "; cin >> e.number;
return s;
}
ostream& operator << (ostream& s, employee& e)
EX6/2: Implements linked list as a template,
demonstrates list used with employee class
{
cout << "\n Name: " << e.name;
cout << "\n Number: " << e.number;
return s;
}
////////////////////////////////////////////////////////////////
template<class TYPE> //struct "link<TYPE>"
struct link //one element of list
{
TYPE data; //data item
link* next; //pointer to next link
};
////////////////////////////////////////////////////////////////
template<class TYPE> //class "linklist<TYPE>"
class linklist //a list of links
{
private:
link<TYPE>* first; //pointer to first link
public:
linklist() //no-argument constructor
{ first = NULL; } //no first link
void additem(TYPE d); //add data item (one link)
void display(); //display all links
};
EX6/3: Implements linked list as a template,
demonstrates list used with employee class
template<class TYPE>
void linklist<TYPE>::additem(TYPE d) //add data item
{
link<TYPE>* newlink = new link<TYPE>; //make a new link
newlink->data = d; //give it data
newlink->next = first; //it points to next link
first = newlink; //now first points to this
}
//--------------------------------------------------------------
template<class TYPE>
void linklist<TYPE>::display() //display all links
{
link<TYPE>* current = first; //set ptr to first link
while( current != NULL ) //quit on last link
{
cout << endl << current->data; //display data
current = current->next; //move to next link
}
}
////////////////////////////////////////////////////////////////
EX6/4: Implements linked list as a template,
demonstrates list used with employee class int main()
{ //lemp is object of
linklist<employee> lemp; //class "linklist<employee>"
employee emptemp; //temporary employee storage
char ans; //user’s response (‘y’ or ‘n’)

do
{
cin >> emptemp; //get employee data from user
lemp.additem(emptemp); //add it to linked list ‘lemp’
cout << "\nAdd another (y/n)? ";
cin >> ans;
}
while(ans != 'n'); //when user is done,
lemp.display(); //display entire linked list
cout << endl;
return 0;
}

Potrebbero piacerti anche