Stacks and Queues COMP171 Fall 2006. Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.

Slides:



Advertisements
Similar presentations
Stack & Queues COP 3502.
Advertisements

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.
0 of 37 Stacks and Queues Lecture of 37 Abstract Data Types To use a method, need to know its essentials: signature and return type o additionally,
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.
Stacks  a data structure which stores data in a Last-in First-out manner (LIFO)  has a pointer called TOP  can be implemented by either Array or Linked.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
Queues CS-212 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed in their.
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.
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.
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
Linked List
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
Stacks and Queues.
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 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
Linked Lists Spring Linked Lists / Slide 2 List Overview * Linked lists n Abstract data type (ADT) * Basic operations of linked lists n Insert,
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.
Objectives of these slides:
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Copyright © 2012 Pearson Education, Inc. 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,
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
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.
Lists, Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
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.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Circular Queues Maitrayee Mukerji. Queues First In – First Out (FIFO) The first element to be inserted is the first one to be retrieved Insertion at one.
CS505 Data Structures and Algorithms
CC 215 Data Structures Queue ADT
Lists CS 3358.
Stacks and Queues.
Queues Queues Queues.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
CMSC 341 Lecture 5 Stacks, Queues
Principles of Computing – UFCFA3-30-1
DATA STRUCTURE SUBMUTTED BY:- MADHU MADHAN Lecturer in computer engg. G.P. MEHAM (ROHTAK)
Lists, Stacks and Queues
Stacks and Queues 1.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
LAB#3 Stacks Nora Albabtin nora albabtin.
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 COMP171 Fall 2006

Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations of stacks using n array n linked list

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

Stack and Queue / Slide 4 Push and Pop * Primary operations: Push and Pop * Push n Add an element to the top of the stack * Pop n 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

Stack and Queue / Slide 5 Implementation of Stacks * Any list implementation could be used to implement a stack n Arrays (static: the size of stack is given initially) n Linked lists (dynamic: never become full) * We will explore implementations based on array and linked list * Let’s see how to use an array to implement a stack first

Stack and Queue / Slide 6 Stack class class Stack { public: Stack(int size = 10);// constructor ~Stack() { delete [] values; }// destructor bool IsEmpty() { return top == -1; } bool IsFull() { return top == maxTop; } double Top(); // examine, without popping void Push(const double x); double Pop(); void DisplayStack(); private: int maxTop;// max stack size = size - 1 int top;// current top of stack double* values;// element array };

Stack and Queue / Slide 7 Stack class  Attributes of Stack maxTop : the max size of stack top : the index of the top element of stack values : point to an array which stores elements of stack  Operations of Stack IsEmpty : return true if stack is empty, return false otherwise IsFull : 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 DisplayStack : print all the data in the stack

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

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

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

Stack and Queue / Slide 11 Array Impln: Stack Top * double Top() n Return the top element of the stack n Unlike Pop, this function does not remove the top element double Stack::Top() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top]; }

Stack and Queue / Slide 12 Array Impln: Printing all the elements * void DisplayStack() n Print all the elements void Stack::DisplayStack() { cout "; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t| |" << endl; }

Stack and Queue / Slide 13 Using Stack int main(void) { Stack stack(5); stack.Push(5.0); stack.Push(6.5); stack.Push(-3.0); stack.Push(-8.0); stack.DisplayStack(); cout << "Top: " << stack.Top() << endl; stack.Pop(); cout << "Top: " << stack.Top() << endl; while (!stack.IsEmpty()) stack.Pop(); stack.DisplayStack(); return 0; } result

Stack and Queue / Slide 14 * 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 Implementation based on Linked List class List { public: List(void) { head = NULL; }// constructor ~List(void);// destructor bool IsEmpty() { return head == NULL; } Node* InsertNode(int index, double x); int FindNode(double x); int DeleteNode(double x); void DisplayList(void); private: Node* head; friend class Stack; };

Stack and Queue / Slide 15 Implementation based on Linked List class Stack : public List { public: Stack() {}// constructor ~Stack() {}// destructor double Top() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else return head->data; } void Push(const double x) { InsertNode(0, x); } double Pop() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else { double val = head->data; DeleteNode(val); return val; } void DisplayStack() { DisplayList(); } }; Note: the stack implementation based on a linked list will never be full.

Stack and Queue / Slide 16 Application: Balancing Symbols * To check that every right brace, bracket, and parentheses must correspond to its left counterpart n 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 and Queue / Slide 17 Array implementation versus linked list implementations * push, pop, top are all constant-time operations in both array implementation and linked list implementation n For array implementation, the operations are performed in very fast constant time

Stack and Queue / Slide 18 Queue Overview * Queue ADT * Basic operations of queue n Enqueuing, dequeuing etc. * Implementation of queue n Array n Linked list

Stack and Queue / Slide 19 Queue ADT * Like a stack, a queue is also a list. However, with a queue, insertion is done at one end, while deletion is performed at the other end. * Accessing the elements of queues follows a First In, First Out (FIFO) order. n Like customers standing in a check-out line in a store, the first customer in is the first customer served.

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

Stack and Queue / Slide 21 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

Stack and Queue / Slide 22 Queue Implementation of Array * There are several different algorithms to implement Enqueue and Dequeue * Naïve way n When enqueuing, the front index is always fixed and the rear index moves forward in the array. front rear Enqueue(3) 3 front rear Enqueue(6) 3 6 front rear Enqueue(9) 3 6 9

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

Stack and Queue / Slide 24 Queue Implementation of Array * A better way n When an item is enqueued, the rear index moves forward. n When an item is dequeued, the front index also moves forward by one element XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) (front) The problem here is that the rear index cannot move beyond the last element in the array.

Stack and Queue / Slide 25 Implementation using Circular Array * Using a circular array * When an element moves past the end of a circular array, it wraps around to the beginning, e.g. n OOOOO7963  4OOOO7963 (after Enqueue(4)) n After Enqueue(4), the rear index moves from 3 to 4. * How to detect an empty or full queue, using a circular array algorithm? n Use a counter of the number of elements in the queue.

Stack and Queue / Slide 26 Queue Implementation of Linked List class Queue { public: Queue(int size = 10);// constructor ~Queue() { delete [] values; }// destructor bool IsEmpty(void); bool IsFull(void); bool Enqueue(double x); bool Dequeue(double & x); void DisplayQueue(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 };

Stack and Queue / Slide 27 Queue Class  Attributes of Queue front/rear : front/rear index counter : number of elements in the queue maxSize : capacity of the queue values : point to an array which stores elements of the queue  Operations of Queue IsEmpty : return true if queue is empty, return false otherwise IsFull : 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 DisplayQueue : print all the data

Stack and Queue / Slide 28 Create Queue * Queue(int size = 10) n Allocate a queue array of size. By default, size = 10. n front is set to 0, pointing to the first element of the array n 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; }

Stack and Queue / Slide 29 IsEmpty & IsFull  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::IsEmpty() { if (counter)return false; elsereturn true; } bool Queue::IsFull() { if (counter < maxSize)return false; elsereturn true; }

Stack and Queue / Slide 30 Enqueue bool Queue::Enqueue(double x) { if (IsFull()) { cout << "Error: the queue is full." << endl; return false; } else { // calculate the new rear position (circular) rear= (rear + 1) % maxSize; // insert new item values[rear]= x; // update counter counter++; return true; }

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

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

Stack and Queue / Slide 33 Using Queue int main(void) { Queue queue(5); 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.DisplayQueue(); double value; queue.Dequeue(value); cout << "Retrieved element = " << value << endl; queue.DisplayQueue(); queue.Enqueue(7); queue.DisplayQueue(); return 0; }

Stack and Queue / Slide 34 Queue Implementation based on Linked List class Queue { public: Queue() {// constructor front = rear = NULL; counter= 0; } ~Queue() {// destructor double value; while (!IsEmpty()) Dequeue(value); } bool IsEmpty() { if (counter) return false; else return true; } void Enqueue(double x); bool Dequeue(double & x); void DisplayQueue(void); private: Node* front;// pointer to front node Node* rear;// pointer to last node int counter;// number of elements };

Stack and Queue / Slide 35 Enqueue void Queue::Enqueue(double x) { Node* newNode=new Node; newNode->data=x; newNode->next=NULL; if (IsEmpty()) { front=newNode; rear=newNode; } else { rear->next=newNode; rear=newNode; } counter++; } 8 rear newNode 5 58

Stack and Queue / Slide 36 Dequeue bool Queue::Dequeue(double & x) { if (IsEmpty()) { cout << "Error: the queue is empty." << endl; return false; } else { x=front->data; Node* nextNode=front->next; delete front; front=nextNode; counter--; } 8 front 5 583

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

Stack and Queue / Slide 38 Result * Queue implemented using linked list will be never full based on array based on linked list