Chapter Objectives. Chapter 7. Stacks. Various Types of Stacks LIFO. Empty Stack. Stacks

Similar documents
Data Structures Using C++ 2E. Chapter 5 Linked Lists

Application of Stacks: Postfix Expressions Calculator (cont d.)

Stacks. Linear data structures

Linked List as an ADT (cont d.)

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Unordered Linked Lists

DATA STRUCTURE - STACK

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Module 2 Stacks and Queues: Abstract Data Types

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

C++ INTERVIEW QUESTIONS

Data Structures and Algorithms C++ Implementation

DATA STRUCTURES USING C

Linked Lists Linked Lists, Queues, and Stacks

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Data Structures and Algorithms V Otávio Braga

Common Data Structures

List, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

CS 2412 Data Structures. Chapter 2 Stacks and recursion

7.1 Our Current Model

Data Structures and Data Manipulation

The C Programming Language course syllabus associate level

Chapter 3: Restricted Structures Page 1

Queue Implementations

Converting a Number from Decimal to Binary

An Incomplete C++ Primer. University of Wyoming MA 5310

1 Abstract Data Types Information Hiding

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Object Oriented Software Design II

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Algorithms and Data Structures

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Pseudo code Tutorial and Exercises Teacher s Version

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Pointers and Linked Lists

Cpt S 223. School of EECS, WSU

10CS35: Data Structures Using C

CSI33 Data Structures

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Data Structures and Algorithms(5)

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Linear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CmpSci 187: Programming with Data Structures Spring 2015

Data Structures and Algorithms Stacks and Queues

Binary storage of graphs and related data

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter 5 Functions. Introducing Functions

Data Structures and Algorithms

Coding conventions and C++-style

Introduction to Stacks

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

St S a t ck a ck nd Qu Q eue 1

Glossary of Object Oriented Terms

STACK Data Structure:

El Dorado Union High School District Educational Services

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

TREE BASIC TERMINOLOGIES

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

Lecture 12 Doubly Linked Lists (with Recursion)

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

STACKS,QUEUES, AND LINKED LISTS

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Data Structure with C

Analysis of a Search Algorithm

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Recursion vs. Iteration Eliminating Recursion

COMPUTER SCIENCE. Paper 1 (THEORY)

C++FA 3.1 OPTIMIZING C++

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Data Structure [Question Bank]

Data Structures. Level 6 C Module Descriptor

Introduction to Data Structures

Introduction to Data Structures and Algorithms

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD


Lecture Notes on Stacks & Queues

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Data Structures and Algorithms

Abstract Data Types. Chapter 2

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Variable Base Interface

C++ Overloading, Constructors, Assignment operator

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Node-Based Structures Linked Lists: Implementation

Transcription:

Chapter Objectives Chapter 7 Stacks Learn about stacks Examine various stack operations Learn how to implement a stack as an array Learn how to implement a stack as a linked list Discover stack applications Learn to use a stack to remove recursion Become aware of the STL class stack Data Structures Using C++ 1 Data Structures Using C++ 2 Stacks Definition: list of homogeneous elements, wherein the addition and deletion of elements occur only at one end, called the top of the stack Last In First Out (LIFO) data structure Used to implement function calls Used to convert recursive algorithms (especially not tail recursive) into nonrecursive algorithms Various Types of Stacks Data Structures Using C++ 3 Data Structures Using C++ 4 LIFO Last In First Out (LIFO) data structure Top element of stack is last element to be added to stack Elements added and removed from one end (top) Item added last are removed first Empty Stack Data Structures Using C++ 5 Data Structures Using C++ 6

Stack Operations Basic Operations on a Stack initializestack: Initializes the stack to an empty state destroystack: Removes all the elements from the stack, leaving the stack empty isemptystack: Checks whether the stack is empty. If empty, it returns true; otherwise, it returns false Data Structures Using C++ 7 Data Structures Using C++ 8 Basic Operations on a Stack isfullstack: Checks whether the stack is full. If full, it returns true; otherwise, it returns false push: Add new element to the top of the stack The input consists of the stack and the new element. Prior to this operation, the stack must exist and must not be full Basic Operations on a Stack top: Returns the top element of the stack. Prior to this operation, the stack must exist and must not be empty. pop: Removes the top element of the stack. Prior to this operation, the stack must exist and must not be empty. Data Structures Using C++ 9 Data Structures Using C++ 10 Example of a Stack Empty Stack Data Structures Using C++ 11 Data Structures Using C++ 12

initializestack and destroystack void stacktype<type>::initializestack() stacktop = 0; //end initializestack void stacktype<type>::destroystack() stacktop = 0; //end destroystack Data Structures Using C++ 13 emptystack and fullstack bool stacktype<type>::isemptystack() return(stacktop == 0); //end isemptystack bool stacktype<type>::isfullstack() return(stacktop == maxstacksize); //end isfullstack Data Structures Using C++ 14 Push Push void stacktype<type>::push(const Type& newitem) if(!isfullstack()) list[stacktop] = newitem; //add newitem at the top //of the stack stacktop++; //increment stacktop else cerr<<"cannot add to a full stack."<<endl; //end push Data Structures Using C++ 15 Data Structures Using C++ 16 Return Top Element Pop Type stacktype<type>::top() assert(stacktop!= 0); return list[stacktop - 1]; //end top //if the stack is empty, //terminate the program //return the element of the //stack indicated by //stacktop - 1 void stacktype<type>::pop() if(!isemptystack()) stacktop--; //decrement stacktop else cerr<<"cannot remove from an empty stack."<<endl; //end pop Data Structures Using C++ 17 Data Structures Using C++ 18

Pop copystack void stacktype<type>::copystack(const stacktype<type>& otherstack) delete [] list; maxstacksize = otherstack.maxstacksize; stacktop = otherstack.stacktop; list = new Type[maxStackSize]; assert(list!= NULL); //copy otherstack into this stack for(int j = 0; j < stacktop; j++) list[j] = otherstack.list[j]; //end copystack Data Structures Using C++ 19 Data Structures Using C++ 20 Copy Constructor Overloading the Assignment Operator (=) stacktype<type>::stacktype(const stacktype<type>& otherstack) list = NULL; copystack(otherstack); //end copy constructor const stacktype<type>& stacktype<type>::operator= (const stacktype<type>& otherstack) if(this!= &otherstack) //avoid self-copy copystack(otherstack); return *this; //end operator= Data Structures Using C++ 21 Data Structures Using C++ 22 Time-Complexity of Operations of class stacktype //Header file: mystack.h Stack Header File #ifndef H_StackType #define H_StackType #include <iostream> #include <cassert> using namespace std; //Place the definition of the class template stacktype, as given //previously in this chapter, here. Data Structures Using C++ 23 //Place the definitions of the member functions, as discussed in //this chapter, here. #endif Data Structures Using C++ 24

GPA Input The program reads an input file consisting of each student s GPA, followed by the student s name. Sample data is: 3.8 Lisa 3.6 John 3.9 Susan 3.7 Kathy 3.4 Jason 3.9 David 3.4 Jack Data Structures Using C++ 25 GPA (Algorithm) 1. Declare the variables. 2. Open the input file. 3. If the input file does not exist, exit the program. 4. Set the output of the floating-point numbers to a fixed decimal format with a decimal point and trailing zeroes. Also, set the precision to two decimal places. 5. Read the GPA and student name. 6. highestgpa = GPA; 7. Initialize the stack. Data Structures Using C++ 26 GPA (Algorithm) 8. while (not end of file) 8.1 if (GPA > highestgpa) 8.1.1 destroystack(stack); 8.1.2 push(stack, student name); 8.1.3 highestgpa = GPA; 8.2 else if(gpa is equal to highestgpa) push(stack, student name); 8.3 Read the GPA and student name; Data Structures Using C++ 27 GPA (Algorithm) 9. Output the highest GPA. 10. Output the names of the students having the highest GPA. Data Structures Using C++ 28 GPA (Sample Run) Input File (Ch7_HighestGPAData.txt) 3.4 Holt 3.2 Bolt 2.5 Colt 3.4 Tom 3.8 Ron 3.8 Mickey 3.6 Pluto 3.5 Donald 3.8 Cindy 3.7 Dome 3.9 Andy 3.8 Fox 3.9 Minnie 2.7 Goofy 3.9 Doc GPA (Sample Run) 3.4 Danny Data Structures Using C++ 29 Data Structures Using C++ 30 Output Highest GPA = 3.90 The students holding the highest GPA are: Doc Minnie Andy

Empty and Nonempty Linked Stack Default Constructor //default constructor linkedstacktype<type>::linkedstacktype() stacktop = NULL; Empty linked stack Nonempty linked stack Data Structures Using C++ 31 Data Structures Using C++ 32 Destroy Stack void linkedstacktype<type>::destroystack() nodetype<type> *temp; //pointer to delete the node while(stacktop!= NULL) //while there are elements //in the stack temp = stacktop; //set temp to point to //the current node stacktop = stacktop->link; //advance stacktop //to the next node delete temp; //deallocate the memory //occupied by temp //end destroystack Data Structures Using C++ 33 initializestack and isstackempty void linkedstacktype<type>:: initializestack() destroystack(); bool linkedstacktype<type>::isemptystack() return(stacktop == NULL); bool linkedstacktype<type>::isfullstack() return false; Data Structures Using C++ 34 Push Push Stack before the push operation Stack and newnode Stack after the statement newnode->link = stacktop; executes Stack after the statement stacktop = newnode; executes Data Structures Using C++ 35 Data Structures Using C++ 36

Return Top Element Pop Type linkedstacktype<type>::top() assert(stacktop!= NULL); return stacktop->info; //end top //if the stack is empty, //terminate the program //return the top element Stack before the pop operation Data Structures Using C++ 37 Data Structures Using C++ 38 Pop Application of Stacks: Postfix Expression Calculator Stack after the statements temp = stacktop; and stacktop = stacktop->link; execute Stack after the statement delete temp; executes Data Structures Using C++ 39 Data Structures Using C++ 40 Application of Stacks: Postfix Expression Calculator Application of Stacks: Postfix Expression Calculator Stack after pushing 6 Stack after retrieving the top two elements and popping twice Stack after pushing 2 Stack after pushing the result of op1 * op2, which is 18 Stack after pushing 3 Stack after pushing the result of op1 + op2, which is 9 Data Structures Using C++ 41 Stack after retrieving the top two elements Stack after popping the element and popping twice Data Structures Using C++ 42

Postfix Expression Calculator (Main Algorithm) Nonrecursive Algorithm to reverse linked list current = first; while(current!= NULL) stack.push(current); current = current->link; llisttype, *newfirst = stack.pop(); current = newfirst; while (!stack.empty()) current->link = stack.pop(); current->link = NULL; Data Structures Using C++ 43 Data Structures Using C++ 44 List After Execution of Statement current = first; Repeated Execution of: stack.push(current); current = current->link; Data Structures Using C++ 45 Data Structures Using C++ 46 STL class stack (Stack Container Adapter) Standard Template Library (STL) provides a class to implement a stack in a program Name of the class defining a stack is stack Name of the header file containing the definition of the class stack is stack Operations on a stack Object Data Structures Using C++ 47 Data Structures Using C++ 48