Stacks and Queues.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Stack & Queues COP 3502.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
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.
 A queue is a waiting line…….  It’s in daily life:-  A line of persons waiting to check out at a supermarket.  A line of persons waiting.
What is a Queue? A queue is a FIFO “first in, first out” structure.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
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 © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
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 CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Abstract Data Type Example l One more example of ADT: l integer linked list using class l A class with dynamic objects: l Copy constructor l Destructor.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
Lecture 9 Feb 26 Announcement/discussion: mid-term # 1 (March 10?) Goals: Queue – implementation using array Application to BFS (breadth-first search)
Lists, Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Stacks, Queues & Deques CSC212.
Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top.
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
1 Queues (Walls & Mirrors - Chapter 7). 2 Overview The ADT Queue Linked-List Implementation of a Queue Array Implementation of a Queue.
Definition Stack is an ordered collection of data items in which access is possible only at one end (called the top of the stack). Stacks are known.
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.”
Objectives of these slides:
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
List, (dynamic) linked list Let’s first forget about ‘classes’, but only a dynamic list. We make lists with ‘classes’ afterwards.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
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,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues 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.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
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.
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.
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Lists, Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
Review Array Array Elements Accessing array elements
CC 215 Data Structures Queue ADT
Stacks and Queues.
Queues Queues Queues.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
CMSC 341 Lecture 5 Stacks, Queues
Cs212: Data Structures Computer Science Department Lab 7: Stacks.
Lists, Stacks and Queues
CSC 143 Queues [Chapter 7].
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
CE 221 Data Structures and Algorithms
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Getting queues right … finally (?)
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Presentation transcript:

Stacks and Queues

More complete list ADT struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor List& operator=(const List& list); // assignment operator bool empty() const; // boolean function void addHead(double x); // add to the head double deleteHead(); // delete the head and get the head element // List& rest(); // get the rest of the list with the head removed // double headElement() const; // get the head element void addEnd(double x); // add to the end double deleteEnd(); // delete the end and get the end element // double endElement(); // get the element at the end bool searchNode(double x); // search for a given x void insertNode(double x); // insert x in a sorted list void deleteNode(double x); // delete x in a sorted list … void print() const; // output int length() const; // count the number of elements private: Node* head; More complete list ADT

Stack Overview Stack ADT Basic operations of stack Pushing, popping etc. Implementations of stacks using array linked list

Stack A stack is a list in which insertion and deletion take place at the same end This end is called top The other end is called bottom Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

Push and Pop Primary operations: Push and Pop Push Pop Add an element to the top of the stack Pop Remove the element at the top of the stack top empty stack A top push an element top push another A B top pop A

Implementation of Stacks Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) We will explore implementations based on array and linked list

Stack ADT class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack double top() const; // keep the stack unchanged // bool full(); // optional // void print() const; private: … }; ‘physical’ constructor/destructor update, ‘logical’ constructor/destructor, composition/decomposition inspection, access Compare with List, see that it’s ‘operations’ that define the type!

Using Stack result int main(void) { Stack stack; stack.push(5.0); stack.print(); cout << "Top: " << stack.top() << endl; stack.pop(); while (!stack.empty()) stack.pop(); return 0; } result

Stack using linked lists struct Node{ public: double data; Node* next; }; class Stack { Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack bool full(); // unnecessary for linked lists double top() const; // keep the stack unchanged void print() const; private: Node* top;

Push (addHead), Pop (deleteHead) void List::addHead(int newdata){ Nodeptr newPtr = new Node; newPtr->data = newdata; newPtr->next = head; head = newPtr; } From ‘addHead’ to ‘push’ void Stack::push(double x){ Node* newPtr = new Node; newPtr->data = x; newPtr->next = top; top = newPtr; }

Implementation based on ‘existing’ linked lists Optional to learn  Good to see that we may ‘re-use’ linked lists

Now let’s implement a stack based on a linked list To make the best out of the code of List, we implement Stack by inheriting List To let Stack access private member head, we make Stack as a friend of List class List { public: List() { head = NULL; } // constructor ~List(); // destructor bool empty() { return head == NULL; } Node* insertNode(int index, double x); int deleteNode(double x); int searchNode(double x); void printList(void); private: Node* head; friend class Stack; };

class Stack : public List { double top() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else return head->data; void push(const double x) { InsertNode(0, x); } double pop() { else { double val = head->data; DeleteNode(val); return val; void printStack() { printList(); } }; from List Note: the stack implementation based on a linked list will never be full.

Stack using arrays class Stack { public: Stack(int size = 10); // constructor ~Stack() { delete [] values; } // destructor bool empty() { return top == -1; } void push(const double x); double pop(); bool full() { return top == maxTop; } double top(); void print(); private: int maxTop; // max stack size = size - 1 int top; // current top of stack double* values; // element array };

Attributes of Stack Operations of Stack maxTop: the max size of stack top: the index of the top element of stack values: point to an array which stores elements of stack Operations of Stack empty: return true if stack is empty, return false otherwise full: return true if stack is full, return false otherwise top: return the element at the top of stack push: add an element to the top of stack pop: delete the element at the top of stack print: print all the data in the stack

Stack constructor Allocate a stack array of size. By default, size = 10. Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e. size – 1. Stack::Stack(int size /*= 10*/) { values = new double[size]; top = -1; maxTop = size - 1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.

void push(const double x); Push an element onto the stack Note top always represents the index of the top element. After pushing an element, increment top. void Stack::push(const double x) { if (full()) // if stack is full, print error cout << "Error: the stack is full." << endl; else values[++top] = x; }

double pop() Pop and return the element at the top of the stack Don’t forgot to decrement top double Stack::pop() { if (empty()) { //if stack is empty, print error cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--];

double top() Return the top element of the stack Unlike pop, this function does not remove the top element double Stack::top() { if (empty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top];

void print() Print all the elements void Stack::print() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t|---------------|" << endl; }

Stack Application: Balancing Symbols To check that every right brace, bracket, and parentheses must correspond to its left counterpart e.g. [( )] is legal, but [( ] ) is illegal Algorithm (1)   Make an empty stack. (2)   Read characters until end of file i.    If the character is an opening symbol, push it onto the stack ii.   If it is a closing symbol, then if the stack is empty, report an error iii.  Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3)   At end of file, if the stack is not empty, report an error

Stack Application: function calls and recursion Take the example of factorial! And run it. #include <iostream> using namespace std; int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ int number; cout << "Enter a positive integer : " << endl;; cin >> number; cout << fac(number) << endl;

Assume the number typed is 3. Tracing the program … Assume the number typed is 3. fac(3): has the final returned value 6 3<=1 ? No. product3 = 3*fac(2) product3=3*2=6, return 6, fac(2): 2<=1 ? No. product2 = 2*fac(1) product2=2*1=2, return 2, fac(1): 1<=1 ? Yes. return 1

Call is to ‘push’ and return is to ‘pop’! fac(1) prod1=1 fac(2) prod2=2*fac(1) fac(3) prod3=3*fac(2)

Array versus linked list implementations push, pop, top are all constant-time operations in both array and linked list implementation For array implementation, the operations are performed in very fast constant time

Queue Overview Queue ADT Basic operations of queue Enqueuing, dequeuing etc. Implementation of queue Linked list Array

Queue A queue is also a list. However, insertion is done at one end, while deletion is performed at the other end. It is “First In, First Out (FIFO)” order. Like customers standing in a check-out line in a store, the first customer in is the first customer served.

Enqueue and Dequeue Primary queue operations: Enqueue and Dequeue Like check-out lines in a store, a queue has a front and a rear. Enqueue – insert an element at the rear of the queue Dequeue – remove an element from the front of the queue Insert (Enqueue) Remove (Dequeue) front rear

Implementation of Queue Just as stacks can be implemented as arrays or linked lists, so with queues. Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks

Queue ADT class Queue { public: Queue(); Queue(Queue& queue); bool empty(); void enqueue(double x); double dequeue(); void print(void); // bool full(); // optional private: … }; ‘physical’ constructor/destructor ‘logical’ constructor/destructor

Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.enqueue(7); return 0; }

Queue using linked lists Struct Node { double data; Node* next; } class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); // bool full(); // optional void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements };

Implementation of some online member functions … class Queue { public: Queue() { // constructor front = rear = NULL; counter = 0; } ~Queue() { // destructor double value; while (!empty()) dequeue(value); bool empty() { if (counter) return false; else return true; void enqueue(double x); double dequeue(); // bool full() {return false;}; void print(void); private: Node* front; // pointer to front node Node* rear; // pointer to last node int counter; // number of elements, not compulsary };

Enqueue (addEnd) 8 5 8 5 void Queue::enqueue(double x) { Node* newNode = new Node; newNode->data = x; newNode->next = NULL; if (empty()) { front = newNode; } else { rear->next = newNode; rear = newNode; counter++; rear 8 5 rear 8 5 newNode

Dequeue (deleteHead) 3 8 5 8 5 double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { x = front->data; Node* nextNode = front->next; delete front; front = nextNode; counter--; return x; front 3 8 5 8 5 front

Printing all the elements void Queue::print() { cout << "front -->"; Node* currNode = front; for (int i = 0; i < counter; i++) { if (i == 0) cout << "\t"; else cout << "\t\t"; cout << currNode->data; if (i != counter - 1) cout << endl; else cout << "\t<-- rear" << endl; currNode = currNode->next; }

Queue using Arrays There are several different algorithms to implement Enqueue and Dequeue Naïve way When enqueuing, the front index is always fixed and the rear index moves forward in the array. front rear Enqueue(3) 3 Enqueue(6) 6 Enqueue(9) 9

Naïve way (cont’d) When dequeuing, the front index is fixed, and the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) rear rear rear = -1 6 9 9 front front front Dequeue() Dequeue() Dequeue()

A better way When enqueued, the rear index moves forward. When dequeued, the front index also moves forward by one element (front) XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) The problem here is that the rear index cannot move beyond the last element in the array.

Using Circular Arrays Using a circular array When an element moves past the end of a circular array, it wraps around to the beginning, e.g. OOOOO7963  4OOOO7963 (after Enqueue(4)) How to detect an empty or full queue, using a circular array algorithm? Use a counter of the number of elements in the queue.

full() is not essential, can be embedded class Queue { public: Queue(int size = 10); // constructor Queue(Queue& queue); // not necessary! ~Queue() { delete [] values; } // destructor bool empty(void); void enqueue(double x); // or bool enqueue(); double dequeue(); bool full(); void print(void); private: int front; // front index int rear; // rear index int counter; // number of elements int maxSize; // size of array queue double* values; // element array }; full() is not essential, can be embedded

Attributes of Queue Operations of Queue front/rear: front/rear index counter: number of elements in the queue maxSize: capacity of the queue values: point to an array which stores elements of the queue Operations of Queue empty: return true if queue is empty, return false otherwise full: return true if queue is full, return false otherwise enqueue: add an element to the rear of queue dequeue: delete the element at the front of queue print: print all the data

Queue constructor Queue(int size = 10) Allocate a queue array of size. By default, size = 10. front is set to 0, pointing to the first element of the array rear is set to -1. The queue is empty initially. Queue::Queue(int size /* = 10 */) { values = new double[size]; maxSize = size; front = 0; rear = -1; counter = 0; }

Empty & Full Since we keep track of the number of elements that are actually in the queue: counter, it is easy to check if the queue is empty or full. bool Queue::empty() { if (counter==0) return true; else return false; } bool Queue::full() { if (counter < maxSize) return false; else return true;

Enqueue Or ‘bool’ if you want void Queue::enqueue(double x) { if (full()) { cout << "Error: the queue is full." << endl; exit(1); // return false; } else { // calculate the new rear position (circular) rear = (rear + 1) % maxSize; // insert new item values[rear] = x; // update counter counter++; // return true;

Dequeue double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { // retrieve the front item x = values[front]; // move front front = (front + 1) % maxSize; // update counter counter--; // return true; return x;

Printing the elements void Queue::print() { cout << "front -->"; for (int i = 0; i < counter; i++) { if (i == 0) cout << "\t"; else cout << "\t\t"; cout << values[(front + i) % maxSize]; if (i != counter - 1) cout << endl; else cout << "\t<-- rear" << endl; }

Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items." << endl; for (int x = 0; x < 5; x++) queue.enqueue(x); cout << "Now attempting to enqueue again..." << endl; queue.enqueue(5); queue.print(); double value; value=queue.dequeue(); cout << "Retrieved element = " << value << endl; queue.enqueue(7); return 0; }

Results Queue implemented using linked list will be never full! based on array based on linked list Queue implemented using linked list will be never full!

Queue applications When jobs are sent to a printer, in order of arrival, a queue. Customers at ticket counters …