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

Similar documents
This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Introduction to Stacks

STACKS,QUEUES, AND LINKED LISTS

7.1 Our Current Model

Data Structures and Algorithms V Otávio Braga

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

Universidad Carlos III de Madrid

Algorithms and Data Structures

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!

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

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

Chapter 3: Restricted Structures Page 1

DATA STRUCTURES USING C

DATA STRUCTURE - STACK

Analysis of a Search Algorithm

Moving from CS 61A Scheme to CS 61B Java

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Linked Lists Linked Lists, Queues, and Stacks

Sequential Data Structures

Stacks. Data Structures and Data Types. Collections

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Module 2 Stacks and Queues: Abstract Data Types

14 Stacks, Queues, And Linked Lists

Algorithms and Data Structures Written Exam Proposed SOLUTION

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

Cpt S 223. School of EECS, WSU

Introduction to Data Structures

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

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

Chapter 5 Instructor's Manual

Habanero Extreme Scale Software Research Project

Common Data Structures

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

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

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

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

CSE 143, Winter 2013 Programming Assignment #2: HTML Validator Due Thursday, July 10, 2014, 11:30 PM

Parallel Programming

COMPUTER SCIENCE. Paper 1 (THEORY)

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

Data Structure [Question Bank]

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Chapter 2: Elements of Java

CompSci-61B, Data Structures Final Exam

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

Explain the relationship between a class and an object. Which is general and which is specific?

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

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

Chapter 7D The Java Virtual Machine

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Data Structures and Algorithms Stacks and Queues

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

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

Binary Heap Algorithms

C Compiler Targeting the Java Virtual Machine

COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

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

D06 PROGRAMMING with JAVA

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Big O and Limits Abstract Data Types Data Structure Grand Tour.

CS 111 Classes I 1. Software Organization View to this point:

Semantic Analysis: Types and Type Checking

Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4)

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

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

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

1 The Java Virtual Machine

CmpSci 187: Programming with Data Structures Spring 2015

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

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

JavaScript: Control Statements I

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

Introduction to Data Structures and Algorithms

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Java Software Structures

Java CPD (I) Frans Coenen Department of Computer Science

Pseudo code Tutorial and Exercises Teacher s Version

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Data Structures and Data Manipulation

Java Interview Questions and Answers

Data Structures In Java

Basic Programming and PC Skills: Basic Programming and PC Skills:

LINKED DATA STRUCTURES

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Lumousoft Visual Programming Language and its IDE

Glossary of Object Oriented Terms

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

Monitors, Java, Threads and Processes

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

The Java Virtual Machine (JVM) Pat Morin COMP 3002

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

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

Transcription:

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

Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of elements to which new elements are added (pushed), and from which elements are removed (popped), at the same end. Stack sometimes referred to as a last in, first out structure (LIFO). In a ueue, elements are removed from the opposite end to which they are added. Queue sometimes referred to as a first in, first out structure (FIFO). 3 Stacks and ueues The difference is the remove operation. add remove add remove 4 CSCU9A3 2

Last In First Out A top B A top C B A top D C B A top E D C B A top D C B A 5 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: n Data stored n Operations on the data n Error conditions associated with operations Example: ADT modeling a simple stock trading system n The data stored are buy/sell orders n The operations supported are w order buy(stock, shares, price) w order sell(stock, shares, price) w void cancel(order) n Error conditions: w Buy/sell a nonexistent stock w Cancel a nonexistent order 6 CSCU9A3 3

The Stack ADT The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think of a spring-loaded plate dispenser. (Pez?) 7 The Stack ADT Main stack operations: n push(object): inserts an element n Object pop(): removes and returns the last inserted element Auxiliary stack operations: n Object peek(): returns the last inserted element without removing it. (Sometimes appears as Object top()) n integer size(): returns the number of elements stored n boolean isempty(): indicates whether no elements are stored 8 CSCU9A3 4

Stack Operations Assume a simple stack for integers. Stack s = new Stack(); s.push(12); s.push(4); s.push( s.top() + 2 ); s.pop() s.push( s.top() ); //what are contents of stack? 9 Stack usage and limitations Write an algorithm to Reverse the contents of an array. How about using a stack? Write a method to print out contents of stack in reverse order. 10 CSCU9A3 5

Stack Interface in Java Java interface corresponding to our Stack ADT Reuires the definition of class EmptyStackException Different from the built-in Java class java.util.stack public interface Stack<E> { public int size(); public boolean isempty(); public Object top() throws EmptyStackException; public void push(e element); public Object pop() throws EmptyStackException; 11 Exceptions Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception Exceptions are said to be thrown by an operation that cannot be executed In the Stack ADT, operations pop and top cannot be performed if the stack is empty Attempting the execution of pop or top on an empty stack throws an EmptyStackException 12 CSCU9A3 6

Applications of Stacks Direct applications n Page-visited history in a Web browser n Undo seuence in a text editor n Chain of method calls in the Java Virtual Machine Indirect applications n Auxiliary data structure for algorithms n Component of other data structures 13 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 n Local variables and return value n 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 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 14 CSCU9A3 7

Array-based Stack Allocate an array of some size (pre-defined) n Maximum N elements in stack Bottom stack element stored at element 0 last index in the array is the top n What is index when stack is empty? Increment top when one element is pushed, decrement after pop 15 Array-based Stack Algorithm size() return top + 1 Algorithm pop() if isempty() then throw EmptyStackException else top top - 1 return S[top + 1] S 0 1 2 t 16 CSCU9A3 8

Array-based Stack (cont.) The array storing the stack elements may become full A push operation will then throw a FullStackException n Limitation of the arraybased implementation n 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 17 Performance and Limitations Performance n Let n be the number of elements in the stack n The space used is O(n) n Each operation runs in time O(1) Limitations n The maximum size of the stack must be defined a priori and cannot be changed n Trying to push a new element into a full stack causes an implementation-specific exception 18 CSCU9A3 9

Common Stack Error Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s.push( i ); // print out contents of stack // while emptying it for(int i = 0; i < s.size(); i++) System.out.println( s.pop() ); // Output? Why? 19 Corrected Version Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s.push( i ); // print out contents of stack // while emptying it int limit = s.size(); for(int i = 0; i < limit; i++) System.out.println( s.pop() ); //or // while(!s.isempty() ) // System.out.println( s.pop() ); 20 CSCU9A3 10

Array-based Stack in Java public class ArrayStack<E> implements Stack<E> { // holds the stack elements private E S[ ]; // index to top element private int top = -1; // constructor public ArrayStack(int capacity) { S = (E[]) new Object[capacity]); public E pop() throws EmptyStackException { if isempty() { throw new EmptyStackException ( Empty stack: cannot pop ); E temp = S[top]; // facilitate garbage collection: S[top] = null; top = top 1; return temp; (other methods of Stack interface) 21 Example use in Java public class Tester { // other methods public void intreverse(integer a[]) { Stack<Integer> s; s = new ArrayStack<Integer>(); public void floatreverse(float f[]) { Stack<Float> s; s = new ArrayStack<Float>(); (code to reverse array f) for(int i = 0; i < a.length; a++) s.push(a[i]); for(int i = 0; i < a.length; a++) a[i] = s.pop(); 22 CSCU9A3 11

Parentheses Matching Each (, {, or [ must be paired with a matching ),, or [ n correct: ( )(( )){([( )]) n correct: ((( )(( )){([( )]) n incorrect: )(( )){([( )]) n incorrect: ({[ ]) n incorrect: ( 23 Parentheses Matching Algorithm Algorithm ParenMatch(X,n): Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number Output: true if and only if 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 24 CSCU9A3 12

HTML Tag Matching For fully-correct HTML, each <name> should pair with a matching </name> <body> <center> <h1> The Little Boat </h1> </center> <p> The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. </p> <ol> <li> Will the salesman die? </li> <li> What color is the boat? </li> <li> And what about Naomi? </li> </ol> </body> The Little Boat The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. 1. Will the salesman die? 2. What color is the boat? 3. And what about Naomi? 25 Infix notation Consider the aithmetic expression: 3 + 4 * (5-2) - 3-1 Binary operators reuires two operands. To evaluate the expression, we use the following rules: * and / have higher precedence than + and -, when operators have the same precedence, we apply them from left to right, brackets change the order of precedence. Hence the following example gives a different answer: 3 + 4 * 5-2 - (3-1) Consider a system of arithmetic with different rules 26 CSCU9A3 13

Reverse Polish With reverse Polish (postfix) notation, no precedence rules or parentheses reuired! In postfix notation, we put the operator after its operands instead of between them. Hence, instead of 5 + 4, we have 5 4 +. 27 Postfix Notation The first expression above, would be re-written as: 3 + 4 * (5-2) - 3-1 3 4 5 2 - * + 3-1 while the second would be written as: 3 + 4 * 5-2 - (3-1) 3 4 5 * + 2-3 1 - - The operands are written in the same order while the operators are now written in the order in which they are to be applied. 28 CSCU9A3 14

Evaluating Postfix Expressions (continued) 29 Examples Let us first apply it to our simple example: 5 4 + Next Token : 5 4 + 5 4 5 9 Answer is 9! With the expression: 3 4 5 2 - * + 3-1 - 2 5 4 3 3 4 3 12 3 15 Next - * + 3-1 - 30 3 15 12 1 12 11 CSCU9A3 15