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



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

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

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!

Universidad Carlos III de Madrid

7.1 Our Current Model

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

HW3: Programming with stacks

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

Introduction to Stacks

STACKS,QUEUES, AND LINKED LISTS

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

Data Structures and Algorithms V Otávio Braga

Analysis of a Search Algorithm

Algorithms and Data Structures Written Exam Proposed SOLUTION

DATA STRUCTURE - STACK

Linked Lists Linked Lists, Queues, and Stacks

CmpSci 187: Programming with Data Structures Spring 2015

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

Lecture 12: Abstract data types

Outline. 1 Denitions. 2 Principles. 4 Implementation and Evaluation. 5 Debugging. 6 References

Data Structures In Java

14 Stacks, Queues, And Linked Lists

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Software Engineering Techniques

Sequential Data Structures

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Chapter 3: Restricted Structures Page 1

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

Data Structures and Algorithms Stacks and Queues

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

Stacks. Linear data structures

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

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

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

Code Refactoring and Defects

Data Structures in the Java API

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

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Cpt S 223. School of EECS, WSU

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

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

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

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

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

Rigorous Software Development CSCI-GA

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

CompSci-61B, Data Structures Final Exam

Programming with Data Structures

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

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

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

cs2010: algorithms and data structures

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

Stacks. Data Structures and Data Types. Collections

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

Lecture Notes on Stacks & Queues

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

TESTING WITH JUNIT. Lab 3 : Testing

Inside the Java Virtual Machine

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

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

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

Abstract Data Types. Chapter 2

The ADT Binary Search Tree

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

Building a Multi-Threaded Web Server

dictionary find definition word definition book index find relevant pages term list of page numbers

Algorithms and Data Structures

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

Lecture J - Exceptions

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

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:

Programming Languages CIS 443

Chapter 8: Bags and Sets

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Moving from CS 61A Scheme to CS 61B Java

Data Structures and Algorithms

The following program is aiming to extract from a simple text file an analysis of the content such as:

Chapter 14 The Binary Search Tree

Introduction to Data Structures

CS11 Java. Fall Lecture 7

Tool-Assisted Unit-Test Generation and Selection Based on Operational Abstractions

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

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Computing Concepts with Java Essentials

Chapter 7: Sequential Data Structures

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Stack Allocation. Run-Time Data Structures. Static Structures

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Habanero Extreme Scale Software Research Project

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

CMSC 202H. ArrayList, Multidimensional Arrays

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

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

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

Transcription:

Outline Computer Science 1 Stacks Mike Jacobson Department of Computer Science University of Calgary Lecture #12 1 2 Applications Array-Based Linked List-Based 4 Additional Information Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 1 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 2 / 20 of a Stack ADT Stack ADT A stack is a collection of objects that can be accessed in last-in, first-out order: The only visible element is the (remaining) one that was most recently added. It is easy to implement such a simple data structure extremely efficiently and it can be used to several several interesting problems. Indeed, a stack is used to execute recursive programs making this one of the more widely used data structures (even though you generally don t notice it!) Stack Interface: public interface Stack<E> { public push(e x); public E peek(); public E pop(); public boolean isempty(); Stack Invariant: The object that is visible at the of the stack is the object that has most recently been pushed onto it (and not yet removed) Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 4 / 20

A Stack Interface: Methods A Stack Interface: Methods 1 void push(e obj): Precondition: Interface invariant a) The input object has been pushed onto the stack (which is otherwise unchanged) 2 E peek() (called in the textbook): Precondition: a) Interface Invariant b) The stack is not empty a) Value returned is the object on the of the stack b) The stack has not been changed Exception: An EmptyStackException is thrown if the stack is empty when this method is called E pop(): Precondition: Same as for peek a) Value returned is the object on the of the stack b) This element has been removed from the stack Exception: An EmptyStackException is thrown if the stack is empty when this method is called 4 boolean isempty(): Precondition: Interface Invariant a) The stack has not been changed. b) Value returned is true if the stack is empty and false otherwise Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 5 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 6 / 20 Applications Example Problem: Initial stack 1) S.peek() 2) S.pop() Consider an expression, given as a string of text, that might include various kinds of brackets. Output: 5 Output: 5 How can we confirm that the brackets in the expression are properly matched? Eg. [( 4) + (2 ( + 6))] Solution using a Stack (provable by induction on the length of the expression): ) S.push() Output: no output 4) S.push(4) Output: no output 5) S.peek() Output: 4 Begin with an empty bounded stack (whose capacity is greater than or equal to the length of the given expression) Sweep over the expression, moving from left to right Push a left bracket onto the stack whenever one is found Try to pop a left bracket off the stack every time a right bracket is seen, checking that these two brackets have the same type Ignore non-bracket symbols Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 7 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 8 / 20

Applications Solution Using a Stack (continued) Two possibilities Then parentheses are matched if and only if: Stack is never empty when we want to pop a left bracket off it, and Compared left and right brackets always do have the same type, and The stack is empty after the last symbol in the expression has been processed. Exercise: trace execution of this algorithm on the preceding example. Dynamic array implementation: stack s contents stored in cells 0,..., 1; element in 1 can use a static array if size of stack is bounded Linked implementation: identify of stack with the head of a singly-linked list works well because stack operations only require access to the of the stack, and linked list operations with the head are especially efficient Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 9 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 / 20 Array-Based Array-Based Using an Array Using an Array Initial Stack Effect of S.pop() Effect of S.push() Effect of S.push(4) 0 1 2 4 5 5??? 0 1 2 4 5 0 1 2 4 5 0 1 2 4 5 4 = 2 = 1 = 2 = Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 11 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 12 / 20

Array-Based Array-Based of Stack Operations Cost of Operations public class ArrayStack<T> { private T[] stack; private int ; public ArrayStack() { = -1; stack = (T[]) new Object[6]; public boolean isempty() { return ( == -1); public int size() { return +1; public void push(t x) { ++; stack[] = x; public T peek() { return stack[]; public T pop() { T e = stack[]; stack[] = null; --; return e; Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 1 / 20 All operations cost Θ(1) (constant time, independent of stack size) Problem: What should we do if the stack size exceeds the array size? modify push to reallocate a larger stack (or use a dynamic array) public void push(t x) { ++; if ( == stack.length) { T [] stacknew = (T[]) new Object[2*stack.length]; System.arraycopy(stackNew,0,stack,0,stack.length); stack = stacknew; stack[] = x; Revised cost: Θ(n) in the worst case, Θ(1) amortized cost Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 14 / 20 Using a Linked List Linked List-Based Using a Linked List Linked List-Based Initial Stack Effect of S.pop() Effect of S.push() Effect of S.push(4) 5 15 15 15 4 15 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 15 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 16 / 20

of Stack Operations Linked List-Based Linked List-Based of Stack Operations (cont.) public class LinkedListStack<T> { private class StackNode<T> { private T value; private StackNode<T> next; private StackNode(T x, StackNode<T> n) { value = x; next = n; private StackNode<T> ; private int size; public LinkedListStack() { size = 0; = (StackNode<T>) null; public boolean isempty() { return (size == 0); public int size() { return size; public void push(t x) { ++size; = new StackNode<T>(x,); public T peek() { return.value; public void pop() { T x =.value; =.next; --size; return x; Cost of stack operations: Θ(1) (independent of stack size) Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 17 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 18 / 20 Additional Information Variation: Bounded Stacks Additional Information Stacks in Java and the Textbook Size-Bounded Stacks Similar to stacks (as defined above) with the following exception: Stacks are created to have a maximum capacity (possibly user-defined so that two constructors are needed) If the capacity would be exceeded when a new element is added to the of the stack then push throws a StackOverflowException and leaves the stack unchanged A static array whose length is the stack s capacity can be used to implement a size-bounded stack, extremely simply and efficiently Most hardware and physical stacks are bounded stacks. in Java 1.6: Java 1.6 includes a Stack class as an extension of the Vector class (a dynamic array). Unfortunately, this implementation is somewhat problematic (Stack inheirit s Vector s methods, too!) of Stacks in the Textbook: Data Structures & Algorithms in Java, Robert Lafore, Chapter 5 s from Scratch using arrays (for a bounded stack with fixed capacity) Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 19 / 20 Mike Jacobson (University of Calgary) Computer Science 1 Lecture #12 20 / 20