Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Similar documents
! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

ADTs: Stacks and Queues

! A data type for which: ! An ADT may be implemented using various. ! Examples:

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. Week 9. elements of the same type.

Queues. Gaddis 18.4, Molly A. O'Neil CS 2308 :: Spring 2016

Lecture Data Structure Stack

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18

CS24 Week 4 Lecture 2

Associate Professor Dr. Raed Ibraheem Hamed

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

[CS302-Data Structures] Homework 2: Stacks

CMPT 225. Lecture 9 Stack

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

Stacks and their Applications

Data Structures And Algorithms

Data Structures G5029

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

CSE 214 Computer Science II Stack

Assertion. C++ Object Oriented Programming Pei-yih Ting NTOU CS

Lists are great, but. Stacks 2

ADTs Stack and Queue. Outline

ITEC2620 Introduction to Data Structures

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

C++ Templates. David Camp

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

STACKS AND QUEUES. Problem Solving with Computers-II

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Contents. Errors in Procedural Programming

Lecture 4 Stack and Queue

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

Data Structures using OOP C++ Lecture 9

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

// The next 4 functions return true on success, false on failure

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

UNIT-2 Stack & Queue

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

Application of Stack (Backtracking)

March 13/2003 Jayakanth Srinivasan,

Chapter 18: Stacks And Queues

Lecture 12 ADTs and Stacks

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

ITI Introduction to Computing II

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Chapter 18: Stacks And Queues. Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CSC 1052 Algorithms & Data Structures II: Stacks

Programming Abstractions

1. Stack Implementation Using 1D Array

Stack Abstract Data Type


Stack and Its Implementation

Data Structures and Algorithms

ITI Introduction to Computing II

CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid:

Lecture No.04. Data Structures

Chapter 18: Stacks And Queues

Programming Abstractions

Linear Data Structure

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Chapter 12 - Templates

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

The Stack and Queue Types

Unit 4: Stacks and Queues

September 10,

CS : Data Structures

What can go wrong in a Java program while running?

Object Oriented Programming COP3330 / CGS5409

Stacks and Their Applications

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

CS 106B Lecture 5: Stacks and Queues

Chapter 3. Object-Based Programming Part I

4.3 Stacks and Queues

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

Project 1: Implementation of the Stack ADT and Its Application

csci 210: Data Structures Stacks and Queues

Stacks and Queues. Chapter Stacks

DATA STRUCTURES AND ALGORITHMS

An Introduction to Queues With Examples in C++

Stacks. Revised based on textbook author s notes.

We will now look at a restriction of the Abstract Sorted List that most operations to run in (1) time: the abstract priority queue.

Top of the Stack. Stack ADT

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

CISC-235. At this point we fnally turned our atention to a data structure: the stack

Transcription:

Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016

The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed in LIFO (last in, first out) order No random access to non-first elements You can only access or remove the most-recently-added element Analogy: A stack of plates or trays in a cafeteria. Clean plates/trays are put on top of the stack, and the next person takes the plate/try on top of the stack. 2

Stack Operations The stack ADT supports the following operations: push: add a value onto the top of the stack If it's a size-limited stack, first make sure the stack isn't full pop: remove the value at the top of the stack Depending on the implementation, sometimes pop returns the value as well isempty: returns true if the stack contains no elements Optionally, a stack can also support the following operations: peek: return the value currently at the top of the stack (without popping it from the stack) isfull: if the stack is size-limited, returns true if the stack has no more space to hold additional elements 3

Stack Illustrated stack.push(3) stack.push(2) stack.push(5) stack.push(1) x = stack.pop() 1 5 2 3 4

Stack Illustrated stack.push(3) 1 stack.push(2) stack.push(5) stack.push(1) x = stack.pop() 5 2 x 3 5

Stack Illustrated stack.push(3) stack.push(2) stack.push(5) stack.push(1) x = stack.pop() 5 x 1 y = stack.pop() 2 3 6

Stack Illustrated stack.push(3) 5 stack.push(2) stack.push(5) stack.push(1) y x = stack.pop() y = stack.pop() 2 3 7

Stack Illustrated stack.push(3) stack.push(2) stack.push(5) stack.push(1) x = stack.pop() 4 6 y 5 y = stack.pop() 2 stack.push(6) 3 stack.push(4) z = stack.pop() 8

Stack Illustrated stack.push(3) 4 stack.push(2) stack.push(5) stack.push(1) x = stack.pop() y = stack.pop() stack.push(6) stack.push(4) z = stack.pop() 6 2 3 z 9

Stack Illustrated stack.push(3) stack.push(2) stack.push(5) stack.push(1) x = stack.pop() 6 z 4 y = stack.pop() 2 stack.push(6) 3 stack.push(4) z = stack.pop() 10

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 5 4 11

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 4 + 5 = 9 12

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 2 7 9 13

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 7-2 = 5 9 14

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 5 9 15

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input 9 * 5 = 45 16

Stack Applications Syntax parsing (e.g., bracket matching, cf. Project 7) Compilers have to do this Evaluating arithmetic expressions in post-fix notation 4 5 + 7 2 - * is equivalent to (4 + 5) * (7-2) Algorithm: Parse input from L to R As you encounter operands, push them onto the stack If you encounter an operator, pop two operands from the stack and apply the operation, then push the result onto the stack Keep going until no more input Precedence rules and parentheses are never needed! 17

Stack Applications "Undo" feature in text editors Recent text changes are kept in a stack Backtracking Imagine you must write code to guide a robot through a maze or labyrinth Every time you reach a decision point, choose a direction you haven't explored yet. If you hit a dead end, you must backtrack......but backtrack to where? To the previous decision point! Algorithm: At every decision point, push all possible choices onto the stack. Pop a choice and go that route. If you hit a dead end, pop the next choice from the stack. 18

Backtracking Decision point @ E4: - choices: North, South H G F E D C B A 0 1 2 3 4 5 6 7 E4: South E4: North 19

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South H G F E D C B A 0 1 2 3 4 5 6 7 D6: South D6: North E4: North 20

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: H G F E D C B A 0 1 2 3 4 5 6 7 D6: North E4: North 21

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: D6: North H G F E D C B A 0 1 2 3 4 5 6 7 E4: North 22

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: D6: North Dead End! Backtrack: H G F E D C B A 0 1 2 3 4 5 6 7 E4: North 23

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: D6: North Dead End! Backtrack: E4: North H G F E D C B A 0 1 2 3 4 5 6 7 24

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: H G F E D C B A D6: North Dead End! Backtrack: E4: North Decision point @ G4: - choices: East, West 0 1 2 3 4 5 6 7 G4: West G4: East 25

Backtracking Decision point @ E4: - choices: North, South E4: South Decision point @ D6: - choices: North, South D6: South Dead End! Backtrack: D6: North Dead End! Backtrack: E4: North Decision point @ G4: - choices: East, West G4: West H G F E D C B A 0 1 2 3 4 5 6 7 G4: East 26

Backtracking Dead End! Backtrack: H G F E D C B A 0 1 2 3 4 5 6 7 G4: East 27

Backtracking Dead End! Backtrack: G4: East H G F E D C B A 0 1 2 3 4 5 6 7 28

Backtracking Dead End! Backtrack: G4: East Success! H G F E D C B A 0 1 2 3 4 5 6 7 This backtracking process is used for many other algorithms as well 29

Hardware Stacks We've already learned about one hardware application of a stack: where function local variables are stored in memory The stack is also used to store the return address during a function call This is how nested function calls work (remember the push/ pop behavior from the Dynamic Memory lecture?) When the function terminates, its stack frame is removed and the return address (where to resume executing code, i.e. where the function call was) is retrieved 30

Stack Terminology Stack overflow The condition resulting from trying to push an element onto a full stack if(!stack.isfull()) stack.push(item); Stack underflow The condition resulting from trying to pop an empty stack if(!stack.isempty()) stack.pop(); 31

Stack Implementations A stack is an ADT, which means it's defined only in terms of the properties of the data and the operations that can be performed on that data Like with the List ADT, there are several data structures we could use to implement a Stack: Linked list (...but really, you've already done this one!) Push == prepend node to list Pop == remove front node from list and return its value Fixed-size array Keep track of top index; stack has maximum size and can be full Dynamic array Keep track of top index; re-size/re-allocate array when full 32

A Fixed-Size Array Stack Class class IntStack { private: int *stackarray; // the stack array int stacksize; // the array size int top; // which array index is the stack top? public: IntStack(int); // constructor IntStack(const IntStack &) // copy constructor ~IntStack(); // destructor } void push(int); int pop(); bool isfull() const; bool isempty() const; 33

Stack: Constructors IntStack::IntStack(int size) { if(size <= 0) size = 1; // or error } stackarray = new int[size]; stacksize = size; top = -1; // empty IntStack::IntStack(const IntStack &rhs) { stackarray = new int[rhs.stacksize]; stacksize = rhs.stacksize; for(int i = 0; i < stacksize; i++) stackarray[i] = rhs.stackarray[i]; } top = rhs.top; 34

Stack: Destructor IntStack::~IntStack() { delete [] stackarray; } 35

Stack: Push void IntStack::push(int item) { assert(!isfull()); // stack overflow! } stackarray[++top] = item; The assert() statement will cause the program to terminate with an error if!isfull() returns false The best way to remember this: assert means "Make sure..." Really easy syntax for error checking & communication Just need to #include <cassert> Runtime error will include the line number of the assert() If you want a helpful error message, too, there's always this hack: assert(!isfull() && "Attempting to push to full stack!"); 36

Stack: Pop int IntStack::pop() { assert(!isempty()); // stack underflow! } return stackarray[top--]; 37

Stack: isfull & isempty bool IntStack::isFull() { return (top == stacksize - 1); // returns true if there is // no empty space on stack } bool IntStack::isEmpty() { return (top == -1); } // returns true if there are no // items on stack 38