COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

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

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Outline and Reading. The Stack ADT ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack.

Stacks. Lecture6: Stacks. Stack Operations. Stack Interface in Java

Stacks Goodrich, Tamassia

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

Stacks Goodrich, Tamassia Stacks

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

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.

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

Data Structures Lecture 5

Foundations of Data Structures

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

COMP9024: Data Structures and Algorithms

Lecture 3 Linear Data Structures

CS212:Data Structure

Lecture 3 Linear Data Structures

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

Stacks Goodrich, Tamassia, Goldwasser Stacks

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

data structures and algorithms lecture 6

DataStruct 5. Stacks, Queues, and Deques

Lecture 3 Linear Data Structures

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

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Stacks Fall 2018 Margaret Reid-Miller

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

CSC148 Week 2. Larry Zhang

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

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

csci 210: Data Structures Stacks and Queues

This lecture. Abstract Data Types (ADTs) The Stack ADT ( 4.2) Stacks. Stack Interface in Java. Exceptions. Abstract data types Stacks Queues

Stacks. Revised based on textbook author s notes.

Data Structures G5029

Data Structures And Algorithms

CSC 273 Data Structures

How many times is the loop executed? middle = (left+right)/2; if (value == arr[middle]) return true;

CIS Fall Data Structures Midterm exam 10/16/2012

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

COSC This week. List ADT. Abstract Data Type (ADT) Lis t ADT Implementations. Data Struc tures and Algorithms

CS350: Data Structures Stacks

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

CT 229 Object-Oriented Programming Continued

CMSC 132: Object-Oriented Programming II. Stack and Queue

COMP 250 Winter stacks Feb. 2, 2016

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CSC148H Week 3. Sadia Sharmin. May 24, /20

COMP 250. Lecture 8. stack. Sept. 25, 2017

File Input and Output

Top of the Stack. Stack ADT

Data Abstraction and Specification of ADTs

Interfaces & Generics

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

Abstract Data Types - Lists Arrays implementa4on Linked- lists implementa4on

Linear Data Structures

Queues Fall 2018 Margaret Reid-Miller

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

CMPT 225. Lecture 9 Stack

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

Stack and Its Implementation

CSE 143 SAMPLE MIDTERM

Basic Data Structures

Data structure and algorithm in Python

Top of the Stack. Stack ADT

Basic Data Structures 1 / 24

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

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

THE UNIVERSITY OF WESTERN AUSTRALIA

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Building Java Programs

Stacks and Queues. Chapter Stacks

LIFO : Last In First Out

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

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

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

The java.util.list ADT

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

CSE 143 SAMPLE MIDTERM SOLUTION

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Csci 102: Sample Exam

Ch02 Data Structures

CSE 143. Lecture 4: Stacks and Queues

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Ch02 Data Structures

Stacks. The unorganized person s data structure. stacks 1

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Largest Online Community of VU Students

CSC 222: Computer Programming II. Spring 2005

CSIS 10B Lab 2 Bags and Stacks

DNHI Homework 3 Solutions List, Stacs and Queues

15. Stacks and Queues

Midterm Exam 2 CS 455, Spring 2011

Stacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

CMPS 390 Data Structures

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

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Application of Stack (Backtracking)

Arrays. Array Definition

Derive From A Linear List Class. Stacks. Derive From ArrayLinearList. Derive From ArrayLinearList. Derive From ArrayLinearList.

== isn t always equal?

Transcription:

COMP250: Stacks Jérôme Waldispühl School of Computer Science McGill University Based on slides from (Goodrich & Tamassia, 2004) 2004 Goodrich, Tamassia

The Stack ADT A Stack ADT is a list that allows only operations at one end of the list (called the top) Main stack operations: push(object): inserts an element at the top of the stack object pop(): removes the object at the top of the stack object top(): returns the last inserted element without removing it (N.B. In Java, this is called peek() ) integer size(): returns the number of elements stored boolean isempty(): indicates whether no elements are stored Last in First out (LIFO) 2004 Goodrich, Tamassia Stacks 2

Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Indirect applications Auxiliary data structure for algorithms Component of other data structures 2004 Goodrich, Tamassia Stacks 3

Method Stack in the JVM The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack When a method is called, the JVM pushes on the stack a frame containing Local variables and return value Program counter, keeping track of the statement being executed When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack Allows for recursion main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { } bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5 2004 Goodrich, Tamassia Stacks 4

Method Stack in the JVM The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack When a method is called, the JVM pushes on the stack a frame containing 2004 Goodrich, Tamassia Local variables and return value Program counter, keeping track of the statement being executed When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack Allows for recursion main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { } foo bar PC = 3 j PC = = 5 1 k m = 6 main PC = 2 i = 5 Stacks 5

Array-based Stack in Java public class ArrayStack { // holds the stack elements private Object S[ ]; // index to top element private int top = -1; // constructor public ArrayStack(int capacity) { S = new Object[capacity]); } An integer top keeps track of the top of the stack. Capacity fixes the size of the array, hence the stack. 2004 Goodrich, Tamassia Stacks 6

Example of array-based Stack X X top Y X Y Z X Y Top() 2004 Goodrich, Tamassia Stacks 7 Push(Y) Push(Z) Pop() Y

Array-based Stack (push) The array storing the stack elements may become full A push operation will then throw a FullStackException Limitation of the arraybased implementation Not intrinsic to the Stack ADT Algorithm push(o) if t = S.length - 1 then throw FullStackException else t t + 1 S[t] o S 0 1 2 t 2004 Goodrich, Tamassia Stacks 8

Array-based Stack (pop) A simple way of implementing the Stack ADT uses an array We add elements from left to right A variable keeps track of the index of the top element Algorithm size() return t + 1 Algorithm pop() if isempty() then throw EmptyStackException else t t - 1 S 0 1 2 t 2004 Goodrich, Tamassia Stacks 9

Performance and Limitations Performance Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) Limitations The maximum size of the stack must be defined a priori and cannot be changed Trying to push a new element into a full stack causes an implementation-specific exception 2004 Goodrich, Tamassia Stacks 10

Stack using a Singly Linked List We can implement a stack with a singly linked list The top element is stored at the first node of the list The space used is O(n) and each operation of the Stack ADT takes O(1) time How? nodes Top =Head elements 2004 Goodrich, Tamassia Stacks 11

Example: Parentheses Matching Each (, {, or [ must be paired with a matching ), }, or [ Correct: ()(()){([()])} Incorrect: )(( )){([( )])} Incorrect: ({[ ])} Incorrect: ( 2004 Goodrich, Tamassia Stacks 12

Parentheses Matching Algorithm Algorithm ParenMatch(X,n): Input: An array X of n tokens, each of which is either a grouping symbol. Output: true if and only if X is well-balanced S new Stack() for i = 0 to n-1 do... 2004 Goodrich, Tamassia Stacks 13

Model What are well-bracketed words? Each opening bracket (e.g. [ ) is associated to one and only one closing bracket (e.g. ] ). Open a bracket before to close it. Reading from left to right, a closing bracket is associated to the last opening bracket screened. Why do we need a stack? Store the opening brackets not already matched. Last in - first out: The last opening bracket seen is the first one to be matched to a closing bracket. 2004 Goodrich, Tamassia Stacks 14

Example ( ( ) ) ( ) Empty stack at the end Push( ( ) Pop() of the scan. All match were valid and all brackets are matched. OK! () () Match! ( ( 2004 Goodrich, Tamassia Stacks 15

Example ( { ) } ( ) { ) Not matching! { ( 2004 Goodrich, Tamassia Stacks 16

Example ( { } ( ( ) () List non empty. Brackets without {} match. Fail! ( ( { ( 2004 Goodrich, Tamassia Stacks 17

Example ( ) ) ) ( ) ( ) Empty stack! Nothing to match. ( 2004 Goodrich, Tamassia Stacks 18

Parentheses Matching Algorithm Algorithm ParenMatch(X,n): Input: An array X of n tokens. Output: true iff all the grouping symbols in X match Let S be an empty stack for i=0 to n-1 do if X[i] is an opening grouping symbol then S.push(X[i]) else if X[i] is a closing grouping symbol then if S.isEmpty() then return false {nothing to match with} if S.pop() does not match the type of X[i] then return false {wrong type} if S.isEmpty() then return true {every symbol matched} else return false {some symbols were never matched} 2004 Goodrich, Tamassia Stacks 19

Midterm Mid-term covers all topics (including queues) 2 rooms (partition based on your last name) Review on Wednesday Oct 21 Vote for topics covered in review session 2004 Goodrich, Tamassia Stacks 20