Starting Out with C++, 3 rd Edition Chapter 18 – Stacks and Queues.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Chapter 6 Queues and Deques.
Stack & Queues COP 3502.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 18: Stacks And Queues.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Queue Overview Queue ADT Basic operations of queue
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Starting Out with C++, 3 rd Edition Chapter 18 Stacks and Queues.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
1 Queues CPS212 Gordon College. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank, food.
1 Queues and Priority Queues Chapter 8. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank,
Stacks and Queues.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
CS 204 Stacks and Queues (not in any book that we are using) From Starting out with C++, 7th edition, by Gaddis, Walters and Muganda (chapter 18, pp
Templates Zhen Jiang West Chester University
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 18 Stacks and Queues.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
131 3/30/98 CSE 143 More Collection ADTs [Sections ]
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Stacks And Queues Chapter 18.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Queues Chapter 5 Queue Definition A queue is an ordered collection of data items such that: –Items can be removed only at one end (the front of the queue)
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
1 Queues Chapter 4. 2 Objectives You will be able to Describe a queue as an ADT. Build a dynamic array based implementation of a queue ADT.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 15 1.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
18 Chapter Stacks and Queues
Chapter 18: Stacks and Queues.
Stacks and Queues.
Stack and Queue APURBO DATTA.
Stacks.
CMSC 341 Lecture 5 Stacks, Queues
Chapter 19: Stacks and Queues.
(not in any book that we are using)
18.5 Linked Queues Like a stack, a queue can be implemented using pointers and nodes Allows dynamic sizing, avoids issue of wrapping indices NULL front.
CSC 143 Stacks [Chapter 6].
Stacks and Queues.
Pointers & Dynamic Data Structures
Queues Dr. Anwar Ghani Lecture 06: Queue Data Structures
Presentation transcript:

Starting Out with C++, 3 rd Edition Chapter 18 – Stacks and Queues

Starting Out with C++, 3 rd Edition Introduction to the Stack ADT A stack is a data structure that stores and retrieves items in a last-in-first-out (LIFO) manner. It’s like the plates in a cafeteria.

Starting Out with C++, 3 rd Edition Applications of Stacks Computer systems use stacks during a program’s execution to store function return addresses, local variables, etc. The good calculators (like HPs) use stacks for performing mathematical operations.

Starting Out with C++, 3 rd Edition 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

Starting Out with C++, 3 rd Edition Stack Operations Push –Causes a value to be stored in (pushed onto) the stack Pop –Retrieves and removes (pops) a value from the stack

Starting Out with C++, 3 rd Edition 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);

Starting Out with C++, 3 rd Edition The Push Operation The state of the stack after each of the push operations:

Starting Out with C++, 3 rd Edition The Pop Operation Now, suppose we execute three consecutive pop operations on the same stack:

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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 ); }; // IntStack.h #endif

Starting Out with C++, 3 rd Edition Contents of IntStack.cpp #include using namespace std; #include “IntStack.h“ IntStack::IntStack ( int size ) { stackArray = new int[size]; stackSize = size; top = -1; } // IntStack::IntStack void IntStack::push(int num) { assert( !isFull() ); stackArray[++top] = num; } // IntStack::push

Starting Out with C++, 3 rd Edition Contents of IntStack.cpp void IntStack::pop ( int &num ) { assert( !isEmpty() ); num = stackArray[top--]; } // InstStack::pop bool IntStack::isFull ( void ) { return top == stackSize – 1; } // IntStack::isFull bool IntStack::isEmpty(void) { return top == -1; } // IntStack::isEmpty

Starting Out with C++, 3 rd Edition Using a Stack – Program #include using namespace std; #include “IntStack.h“ void main(void) { IntStack stack(5); int catchVar; cout << "Pushing 5\n"; stack.push(5); cout << "Pushing 10\n"; stack.push(10); cout << "Pushing 15\n"; stack.push(15); cout << "Pushing 20\n"; stack.push(20); cout << "Pushing 25\n"; stack.push(25);

Starting Out with C++, 3 rd Edition Using a Stack – Program (cont) 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; } // main

Starting Out with C++, 3 rd Edition Pushing 5 Pushing 10 Pushing 15 Pushing 20 Pushing 25 Popping Using a Stack – Output

Starting Out with C++, 3 rd Edition Using a Stack – Explanation In the program, the constructor is called with the argument 5. This sets up the member variables as shown below. Since top is set to –1, the stack is empty

Starting Out with C++, 3 rd Edition Using a Stack – Explanation (cont) Below 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.

Starting Out with C++, 3 rd Edition Using a Stack – Explanation (cont) Below 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.

Starting Out with C++, 3 rd Edition Using a Stack – Explanation (cont) 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. The next slide depicts the state of the class members, and the num parameter, just after the first value is popped off the stack.

Starting Out with C++, 3 rd Edition Using a Stack – Explanation (cont)

Starting Out with C++, 3 rd Edition Implementing Other Stack Operations The MathStack class demonstrates functions for stack-based arithmetic like some calculators use. The notation for doing stack-based arithmetic is called reversed Polish notation.

Starting Out with C++, 3 rd Edition Dynamic Stacks A dynamic stack is built using 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 is never full, as long as the system has enough free memory.

Starting Out with C++, 3 rd Edition DynIntStack.h – Program #include “Node.h” class DynIntStack { private: Node *top; public: DynIntStack ( void ) { top = NULL; } void push ( int ); void pop ( int & ); bool isEmpty ( void ); }; // DynIntStack

Starting Out with C++, 3 rd Edition DynIntStack.cpp – Program #include using namespace std; #include “DynIntStack.h“ void DynIntStack::push ( int num ) { stackNode *newNode = new Node( num ); if ( isEmpty() ) top = newNode; else { newNode->next = top; top = newNode; } // else } // DynIntStack::push

Starting Out with C++, 3 rd Edition DynIntStack.cpp – Program (cont) void DynIntStack::pop ( int &num ) { stackNode *temp; assert( !isEmpty() ); num = top->value; temp = top->next; delete top; top = temp; } // DynIntStack::pop bool DynIntStack::isEmpty ( void ) { return !top; } // DynIntStack::isEmpty

Starting Out with C++, 3 rd Edition The STL stack Container The STL stack container may be implemented as a vector, a list, or a deque (which you will learn about later in this chapter). Because the stack container is used to adapt these other containers, it is often referred to as a container adapter.

Starting Out with C++, 3 rd Edition The STL stack Container Here are examples of how to declare a stack of int s, implemented as a vector, a list, and a deque. stack > iStack; // Vector stack stack > iStack;// List stack stack iStack;// Default – deque stack The stack container’s member functions are listed and described in the book.

Starting Out with C++, 3 rd Edition STL stack – Program #include #include #include using namespace std; void main ( void ) { int x; stack > iStack; for ( x = 2; x < 8; x += 2 ) { cout << "Pushing " << x << endl; iStack.push(x); } // for 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(); } // for } // main

Starting Out with C++, 3 rd Edition STL stack – Output Pushing 2 Pushing 4 Pushing 6 The size of the stack is 3 Popping 6 Popping 4 Popping 2

Starting Out with C++, 3 rd Edition 18.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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition Queue Operations Think of queues as having a front and a rear. This is illustrated below.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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);

Starting Out with C++, 3 rd Edition Queue Operations Below illustrates the state of the queue after each of the enqueue operations.

Starting Out with C++, 3 rd Edition Queue Operations Now let's see how dequeue operations are performed. Below illustrates the state of the queue after each of three consecutive dequeue operations

Starting Out with C++, 3 rd Edition Queue Operations When the last dequeue 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. We implement the queue as a circular array.

Starting Out with C++, 3 rd Edition 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 ); }; // IntQueue

Starting Out with C++, 3 rd Edition Contents of IntQueue.cpp # include #include "IntQueue.h“ IntQueue::IntQueue(int s) { queueArray = new int[s]; queueSize = s; front = 0; rear = 0; numItems = 0; } // IntQueue::IntQueue IntQueue::~IntQueue(void) { delete [] queueArray; } IntQueue::~IntQueue

Starting Out with C++, 3 rd Edition Contents of IntQueue.cpp void IntQueue::enqueue(int num) { assert( !isFull() ); rear = (rear + 1) % queueSize; queueArray[rear] = num; numItems++; } // IntQueue::enqueue void IntQueue::dequeue(int &num) { assert( !isEmpty() ); front = (front + 1) % queueSize; num = queueArray[front]; numItems--; } // IntQueue::dequeue

Starting Out with C++, 3 rd Edition Contents of IntQueue.cpp bool IntQueue::isEmpty ( void ) { return numItems == 0; } // IntQueue::isEmpty bool IntQueue::isFull ( void ) { return numItems < queueSize); } // IntQueue::isFull void IntQueue::clear ( void) { front = queueSize - 1; rear = queueSize - 1; numItems = 0; } // IntQueue::clear

Starting Out with C++, 3 rd Edition Using Queues – Program #include using namespace std; #include "intqueue.h" void main ( void ) { IntQueue iQueue( 5 ); cout << "Enqueuing 5 items...\n"; for ( int x = 0; x < 5; x++ ) iQueue.enqueue(x); cout << "Now attempting to enqueue again...\n"; iQueue.enqueue(5); cout << "The values in the queue were:\n"; while ( !iQueue.isEmpty() ) { int value; iQueue.dequeue( value ); cout << value << endl; } // while } // main

Starting Out with C++, 3 rd Edition Using Queues – Output Enqueuing 5 items... Now attempting to enqueue again... The queue is full. The values in the queue were: 0

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition Dynamic Queues Below shows the structure of a dynamic queue.

Starting Out with C++, 3 rd Edition Contents of DynIntQueue.h #include "Node.h" class DynIntQueue { private: Node *front; Node *rear; int numItems; public: DynIntQueue ( void ); ~DynIntQueue ( void ); void enqueue ( int ); void dequeue ( int & ); bool isEmpty ( void ); void clear ( void ); }; // DynIntQueue

Starting Out with C++, 3 rd Edition Contents of DynIntQueue.cpp #include #include "dynintqueue.h“ DynIntQueue::DynIntQueue(void) { front = NULL; rear = NULL; numItems = 0; } // DynIntQueue::DynIntQueue DynIntQueue::~DynIntQueue(void) { clear(); } // DynIntQueue::~DynIntQueue

Starting Out with C++, 3 rd Edition Contents of DynIntQueue.cpp void DynIntQueue::enqueue(int num) { Node *newNode ( num ); if ( isEmpty() ) { front = newNode; rear = newNode; } // if else { rear->next = newNode; rear = newNode; } // else numItems++; } // DynIntQueue::enqueue

Starting Out with C++, 3 rd Edition Contents of DynIntQueue.cpp void DynIntQueue::dequeue(int &num) { Node *temp; assert( !isEmpty() ); num = front->value; temp = front->next; delete front; front = temp; numItems--; } // DynIntQueue::dequeue

Starting Out with C++, 3 rd Edition Contents of DynIntQueue.cpp bool DynIntQueue::isEmpty ( void ) { return numItems == 0; } // DynIntQueue::isEmpty void DynIntQueue::clear ( void ) { int value; while ( !isEmpty() ) dequeue(value); } // DynIntQueue::clear

Starting Out with C++, 3 rd Edition Using Dynamic Queues – Output #include using namespace std; #include "dynintqueue.h" void main(void) { DynIntQueue iQueue; cout << "Enqueuing 5 items...\n"; for ( int x = 0; x < 5; x++ ) iQueue.enqueue(x); cout << "The values in the queue were:\n"; while ( !iQueue.isEmpty() ) { int value; iQueue.dequeue(value); cout << value << endl; } // while } // main

Starting Out with C++, 3 rd Edition Using Dynamic Queues – Output Enqueuing 5 items... The values in the queue were:

Starting Out with C++, 3 rd Edition The STL deque and queue Containers A deque (pronounced "deck") 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.

Starting Out with C++, 3 rd Edition 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 described in the book.

Starting Out with C++, 3 rd Edition Using STL deque – Program #include #include using namespace std; void main ( void ) { int x; deque iDeque; cout << "I will now enqueue items...\n"; for ( x = 2; x < 8; x += 2 ) { cout << "Pushing " << x << endl; iDeque.push_back(x); } // for cout << "I will now dequeue items...\n"; for ( x = 2; x < 8; x += 2 ) { cout << "Popping " << iDeque.front() << endl; iDeque.pop_front(); } // for } // main

Starting Out with C++, 3 rd Edition Using STL deques – Output I will now enqueue items... Pushing 2 Pushing 4 Pushing 6 I will now dequeue items... Popping 2 Popping 4 Popping 6

Starting Out with C++, 3 rd Edition The queue Container Adapter The queue container adapter can be built upon vector s, list s, or deque s. By default, it uses deque as its base.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition Using STL queue – Program #include #include using namespace std; void main ( void ) { int x; queue iQueue; cout << "I will now enqueue items...\n"; for ( x = 2; x < 8; x += 2 ) { cout << "Pushing " << x << endl; iQueue.push(x); } // for cout << "I will now dequeue items...\n"; for ( x = 2; x < 8; x += 2 ) { cout << "Popping " << iQueue.front() << endl; iQueue.pop(); } // for } // main

Starting Out with C++, 3 rd Edition Using STL queue – Output I will now enqueue items... Pushing 2 Pushing 4 Pushing 6 I will now dequeue items... Popping 2 Popping 4 Popping 6