Stack and Queue

Information about Stack and Queue

Published on June 4, 2009

Author: ankush85

Source: authorstream.com

Content

Stack and Queue : Stack and Queue Stack Overview : Stack Overview Stack ADT Basic operations of stack Pushing, popping etc. Implementations of stacks using array linked list The Stack ADT : The Stack ADT A stack is a list with the restriction that insertions and deletions can only be performed at the top of the list The other end is called bottom Fundamental operations: Push: Equivalent to an insert Pop: Deletes the most recently inserted element Top: Examines the most recently inserted element Stack ADT : Stack ADT Stacks are less flexible but are more efficient and easy to implement Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved Push and Pop : Push and Pop Primary operations: Push and Pop Push Add an element to the top of the stack Pop Remove the element at the top of the stack top empty stack push an element push another pop Implementation of Stacks : 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 Let’s see how to use an array to implement a stack first Array Implementation : Array Implementation Need to declare an array size ahead of time Associated with each stack is TopOfStack for an empty stack, set TopOfStack to -1 Push (1)   Increment TopOfStack by 1. (2)   Set Stack[TopOfStack] = X Pop (1)   Set return value to Stack[TopOfStack] (2)   Decrement TopOfStack by 1 These operations are performed in very fast constant time Stack class : 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(); 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 class : 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 Create Stack : Create Stack The constructor of Stack Allocate a stack array of size. By default, size = 10. When the stack is full, top will have its maximum value, i.e. size – 1. Initially top is set to -1. It means the stack is empty. Stack::Stack(int size /*= 10*/) { maxTop = size - 1; values = new double[size]; top = -1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization. Push Stack : Push Stack void Push(const double x); Push an element onto the stack If the stack is full, print the error information. Note top always represents the index of the top element. After pushing an element, increment top. void Stack::Push(const double x) { if (IsFull()) cout << "Error: the stack is full." << endl; else values[++top] = x; } Pop Stack : Pop Stack double Pop() Pop and return the element at the top of the stack If the stack is empty, print the error information. (In this case, the return value is useless.) Don’t forgot to decrement top double Stack::Pop() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--]; } } Stack Top : Stack Top double Top() Return the top element of the stack 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]; } Printing all the elements : Printing all the elements void DisplayStack() Print all the elements void Stack::DisplayStack() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t|---------------|" << endl; } Using Stack : 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 Slide 16: Now let us 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; }; Implementation based on Linked List : 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. Balancing Symbols : 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 Postfix Expressions : Postfix Expressions Calculate 4.99 * 1.06 + 5.99 + 6.99 * 1.06 Need to know the precedence rules Postfix (reverse Polish) expression 4.99 1.06 * 5.99 + 6.99 1.06 * + Use stack to evaluate postfix expressions When a number is seen, it is pushed onto the stack When an operator is seen, the operator is applied to the 2 numbers that are popped from the stack. The result is pushed onto the stack Example evaluate 6 5 2 3 + 8 * + 3 + * The time to evaluate a postfix expression is O(N) processing each element in the input consists of stack operations and thus takes constant time Slide 20:  Queue Overview : Queue Overview Queue ADT Basic operations of queue Enqueuing, dequeuing etc. Implementation of queue Array Linked list Queue ADT : 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. Like customers standing in a check-out line in a store, the first customer in is the first customer served. The Queue ADT : The Queue ADT Another form of restricted list Insertion is done at one end, whereas deletion is performed at the other end Basic operations: enqueue: insert an element at the rear of the list dequeue: delete the element at the front of the list First-in First-out (FIFO) list Enqueue and Dequeue : 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) rear front Implementation of Queue : 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 Implementation of Array : Queue Implementation of Array 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. Enqueue(3) 3 Enqueue(6) 3 6 Enqueue(9) 3 6 9 Queue Implementation of Array : Queue Implementation of Array Naïve way When enqueuing, the front index is always fixed and the rear index moves forward in the array. When dequeuing, the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) Dequeue() 6 9 Dequeue() Dequeue() 9 rear = -1 Queue Implementation of Array : Queue Implementation of Array Better way When an item is enqueued, make the rear index move forward. When an item is dequeued, the front index moves by one element towards the back of the queue (thus removing the front item, so no copying to neighboring elements is needed). 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. Implementation using Circular Array : 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. OOOOO7963 ? 4OOOO7963 (after Enqueue(4)) After Enqueue(4), the rear index moves from 3 to 4. Empty or Full? : Empty or Full? Empty queue back = front - 1 Full queue? the same! Reason: n values to represent n+1 states Solutions Use a boolean variable to say explicitly whether the queue is empty or not Make the array of size n+1 and only allow n elements to be stored Use a counter of the number of elements in the queue Queue Implementation of Linked List : 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 }; Queue Class : 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 Create Queue : Create Queue 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; } IsEmpty & IsFull : 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; else return true; } bool Queue::IsFull() { if (counter < maxSize) return false; else return true; } Enqueue : 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; } } Dequeue : 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; } } Printing the elements : Printing the elements void Queue::DisplayQueue() { 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 : 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 Implementation based on Linked List : Stack 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 }; Enqueue : 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 rear newNode 5 5 8 Dequeue : 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 5 8 3 front Printing all the elements : Printing all the elements void Queue::DisplayQueue() { 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; } } Result : Result Queue implemented using linked list will be never full based on array based on linked list

Related presentations


Other presentations created by ankush85

Nanotechnology
03. 04. 2009
0 views

Nanotechnology

Human Resource Management System
06. 03. 2009
0 views

Human Resource Management System

Nanotechnology
27. 03. 2009
0 views

Nanotechnology

INTRODUCTION TO NANOTECHNOLOGY
20. 11. 2009
0 views

INTRODUCTION TO NANOTECHNOLOGY

Nanotechnology in Sports
22. 11. 2009
0 views

Nanotechnology in Sports

Computer Architecture
14. 07. 2009
0 views

Computer Architecture

HR
18. 03. 2009
0 views

HR

Hospital Management System
08. 04. 2009
0 views

Hospital Management System

Welcome to Visual Basic
06. 03. 2009
0 views

Welcome to Visual Basic

HTML
20. 04. 2009
0 views

HTML

Computer Languages
03. 06. 2013
0 views

Computer Languages

Taking Care of Computer
03. 06. 2013
0 views

Taking Care of Computer

Understanding Camera
16. 10. 2012
0 views

Understanding Camera

Photography Technical Terms
25. 09. 2012
0 views

Photography Technical Terms

Basics of Photography
25. 09. 2012
0 views

Basics of Photography

AIR MUSCLES
03. 01. 2012
0 views

AIR MUSCLES

Molecular Nanotechnology
24. 11. 2009
0 views

Molecular Nanotechnology

Nanotech Innovation
22. 11. 2009
0 views

Nanotech Innovation

FINANCIAL  MARKET
16. 05. 2009
0 views

FINANCIAL MARKET

Operating System
19. 04. 2009
0 views

Operating System

Management Control
10. 07. 2009
0 views

Management Control

Accounting Principles
01. 07. 2009
0 views

Accounting Principles

Balance Sheet
21. 07. 2009
0 views

Balance Sheet

Balance Sheet Auditing
01. 07. 2009
0 views

Balance Sheet Auditing

BRANCH AND BOUND
05. 03. 2009
0 views

BRANCH AND BOUND

THE  THREE  BRANCHES  OF GOVERNMENT
13. 06. 2009
0 views

THE THREE BRANCHES OF GOVERNMENT

Structure of Atom
11. 05. 2009
0 views

Structure of Atom

Compression Techniques
05. 03. 2009
0 views

Compression Techniques

DYNAMIC PROGRAMMING
06. 03. 2009
0 views

DYNAMIC PROGRAMMING

Quantum Mechanics
25. 08. 2009
0 views

Quantum Mechanics

Marketing Plan
19. 06. 2009
0 views

Marketing Plan

Book Keeping
24. 06. 2009
0 views

Book Keeping

DFDS
02. 10. 2008
0 views

DFDS

Semiconductors
25. 04. 2009
0 views

Semiconductors

Organic  Chemistry
28. 04. 2009
0 views

Organic Chemistry

Atoms Molecules and Ions
17. 06. 2009
0 views

Atoms Molecules and Ions

Covalent Bond
25. 04. 2009
0 views

Covalent Bond

Cost Accounting Standards
25. 06. 2009
0 views

Cost Accounting Standards

Crisis Management
19. 06. 2009
0 views

Crisis Management

Marketing
18. 03. 2009
0 views

Marketing

Business Strategy
27. 04. 2009
0 views

Business Strategy

Time Management
23. 03. 2009
0 views

Time Management

Networking Protocols
23. 05. 2009
0 views

Networking Protocols

Network Layer
23. 05. 2009
0 views

Network Layer

Final Accounts
24. 06. 2009
0 views

Final Accounts

ARTIFICIAL  INTELLIGENCE
03. 04. 2009
0 views

ARTIFICIAL INTELLIGENCE

Play with C
08. 04. 2009
0 views

Play with C

Software Development Cycle
23. 03. 2009
0 views

Software Development Cycle

THE GREEDY METHOD
06. 03. 2009
0 views

THE GREEDY METHOD

JOB SEQUENCING
06. 03. 2009
0 views

JOB SEQUENCING

Electricity and Magnetism
29. 04. 2009
0 views

Electricity and Magnetism

Optical Fiber
24. 05. 2009
0 views

Optical Fiber

Quality Assurance
06. 03. 2009
0 views

Quality Assurance

Object-oriented Design
11. 04. 2009
0 views

Object-oriented Design

A.R. Rahman
08. 03. 2009
0 views

A.R. Rahman

Hollywood Female Celebrities
13. 03. 2009
0 views

Hollywood Female Celebrities

Flow nets
04. 09. 2009
0 views

Flow nets

Energy and Nanotechnology
22. 11. 2009
0 views

Energy and Nanotechnology

LOGIC  DESIGN
06. 03. 2009
0 views

LOGIC DESIGN

VB-IDE
06. 03. 2009
0 views

VB-IDE

DLF IPL FINAL
25. 05. 2009
0 views

DLF IPL FINAL

MINIMUM SPANNING TREES
06. 03. 2009
0 views

MINIMUM SPANNING TREES

CPU Scheduling
05. 03. 2009
0 views

CPU Scheduling

Virtual Memory
05. 03. 2009
0 views

Virtual Memory

POK
09. 05. 2009
0 views

POK

2D Transformations
05. 03. 2009
0 views

2D Transformations

Greedy Algorithms
05. 03. 2009
0 views

Greedy Algorithms

BACKTRACKING
05. 03. 2009
0 views

BACKTRACKING

DIVIDE And CONQUER
06. 03. 2009
0 views

DIVIDE And CONQUER

ELEMENTARY DATA STRUCTURES
06. 03. 2009
0 views

ELEMENTARY DATA STRUCTURES

JPEG Compression
06. 03. 2009
0 views

JPEG Compression

Mpeg-compression
06. 03. 2009
0 views

Mpeg-compression

NP - HARD
06. 03. 2009
0 views

NP - HARD

TRAVELLING SALESPERSON PROBLEM
06. 03. 2009
0 views

TRAVELLING SALESPERSON PROBLEM

VBA Introduction
06. 03. 2009
0 views

VBA Introduction

Introduction to Java
09. 03. 2009
0 views

Introduction to Java

Java  Basics
09. 03. 2009
0 views

Java Basics

Heuristic Search
13. 03. 2009
0 views

Heuristic Search

HSM
19. 03. 2009
0 views

HSM

Tata's  Nano  Car
25. 03. 2009
0 views

Tata's Nano Car

Air Cranes
08. 04. 2009
0 views

Air Cranes

Newborn Care
10. 04. 2009
0 views

Newborn Care

Photosynthesis Process
10. 04. 2009
0 views

Photosynthesis Process

ActionScript
13. 04. 2009
0 views

ActionScript

Xml
15. 04. 2009
0 views

Xml

Snakes mis use
17. 04. 2009
0 views

Snakes mis use

Php Web Development
21. 04. 2009
0 views

Php Web Development

Cricket Intro
21. 04. 2009
0 views

Cricket Intro

Cricket Umpiring and Rules
21. 04. 2009
0 views

Cricket Umpiring and Rules

Arm and Forearm
23. 04. 2009
0 views

Arm and Forearm

Elements Ions Isotopes
25. 04. 2009
0 views

Elements Ions Isotopes

Chemical Bond
25. 04. 2009
0 views

Chemical Bond

Discovering Newtons Laws
29. 04. 2009
0 views

Discovering Newtons Laws

FreeFall
29. 04. 2009
0 views

FreeFall

Digital photography
26. 04. 2009
0 views

Digital photography

Health Effects of Alcohol
26. 04. 2009
0 views

Health Effects of Alcohol

Poetry Terminology
27. 04. 2009
0 views

Poetry Terminology

Indian Force
05. 05. 2009
0 views

Indian Force

Machine Intelligence
14. 05. 2009
0 views

Machine Intelligence

Data Link Layer
16. 05. 2009
0 views

Data Link Layer

Database Development Cycle
15. 05. 2009
0 views

Database Development Cycle

Queue
15. 05. 2009
0 views

Queue

Presentaion Skills
23. 04. 2009
0 views

Presentaion Skills

Network Layers
23. 05. 2009
0 views

Network Layers

Narmada Dam, India
23. 05. 2009
0 views

Narmada Dam, India

User Datagram Protocol
24. 05. 2009
0 views

User Datagram Protocol

Linear Momentum
28. 05. 2009
0 views

Linear Momentum

Information Management
19. 06. 2009
0 views

Information Management

Role of Senior Management
19. 06. 2009
0 views

Role of Senior Management

Wake Up India
07. 06. 2009
0 views

Wake Up India

Adobe Flex 3.0
13. 06. 2009
0 views

Adobe Flex 3.0

Adobe Flex Presentation
13. 06. 2009
0 views

Adobe Flex Presentation

Introduction to Adobe Flex
13. 06. 2009
0 views

Introduction to Adobe Flex

Adobe Flash Media Server
13. 06. 2009
0 views

Adobe Flash Media Server

Dreamweaver
13. 06. 2009
0 views

Dreamweaver

Adobe Flash
13. 06. 2009
0 views

Adobe Flash

Flash CS4 Professional
13. 06. 2009
0 views

Flash CS4 Professional

Adobe Flash Lite
13. 06. 2009
0 views

Adobe Flash Lite

Digital Camera
13. 06. 2009
0 views

Digital Camera

Mozilla_Firefox
15. 06. 2009
0 views

Mozilla_Firefox

Managerial Accounting
27. 06. 2009
0 views

Managerial Accounting

Accounting  Information  System
01. 07. 2009
0 views

Accounting Information System

RETAILING AND MARKETING
06. 07. 2009
0 views

RETAILING AND MARKETING

ACCOUNTING IN BUSINESS
05. 07. 2009
0 views

ACCOUNTING IN BUSINESS

STRATEGIC RETAIL MANAGEMENT
05. 07. 2009
0 views

STRATEGIC RETAIL MANAGEMENT

Reiki
01. 08. 2009
0 views

Reiki

Using Buttons in PowerPoint
26. 04. 2009
0 views

Using Buttons in PowerPoint

Nanotechnology  for  Students
21. 08. 2009
0 views

Nanotechnology for Students

NANOSCIENCE
25. 08. 2009
0 views

NANOSCIENCE

Fundamentals of Nanoscience
27. 08. 2009
0 views

Fundamentals of Nanoscience

Nanoscience in Nature
27. 08. 2009
0 views

Nanoscience in Nature

Applied Mechanics
04. 09. 2009
0 views

Applied Mechanics

Accounts Payable Training
27. 06. 2009
0 views

Accounts Payable Training