1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Stack & Queues COP 3502.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Topic 15 Implementing and Using Stacks
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Topic 15 Implementing and Using Stacks
Class 4: Stacks. cis 335 Fall 2001 Barry Cohen What is a stack? n A stack is an ordered sequence of items, of which only the last (‘top’) item can be.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures and Algorithms
Stacks Chapter 5. Overview n The stack ADT n Exceptional situations n Stack implementations stacks in Javastacks in Java.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Stack. Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
1 CSC 321: Data Structures Fall 2012 Lists, stacks & queues  Collection classes: ─List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap,
Lecture6: Stacks Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Data Structures & Algorithms
Stacks Nour El-Kadri CSI Stacks Software stacks are abstract data types (structures) similar to physical stacks, Plates Trays Books PEZ dispenser.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
CHP-3 STACKS.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
1 CSC 321: Data Structures Fall 2013 Lists, stacks & queues  Collection classes: ─List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap,
1 CSC 533: Programming Languages Spring 2014 Subprogram implementation  subprograms (procedures/functions/subroutines)  subprogram linkage  parameter.
Click to edit Master text styles Stacks Data Structure.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks.
CSC 533: Programming Languages Spring 2015
Stacks 12/7/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Stacks.
CSC 321: Data Structures Fall 2018 Lists, stacks & queues
Topic 15 Implementing and Using Stacks
Stacks Chapter 5.
CSC 533: Programming Languages Spring 2018
CSC 533: Programming Languages Spring 2019
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack  application: parenthesis/delimiter matching  postfix expression evaluation  run-time stack

2 Lists & stacks list ADT DATA:sequence of items OPERATIONS:add item, look up item, delete item, check if empty, get size, … e.g., array, ArrayList, DeckOfCards, Dictionary, … stack ADT  a stack is a special kind of (simplified) list  can only add/delete/look at one end (commonly referred to as the top) DATA:sequence of items OPERATIONS:push on top, peek at top, pop off top, check if empty, get size these are the ONLY operations allowed on a stack — stacks are useful because they are simple, easy to understand — each operation is O(1)

3 Stack examples  PEZ dispenser  pile of cards  cars in a driveway  method activation records (later) a stack is also known as  push-down list  last-in-first-out (LIFO) list top 1 2 pop: removes item at top top peek returns item at top  top push: adds item at the top 4

4 Stack exercise start with empty stack PUSH 1 PUSH 2 PUSH 3 PEEK PUSH 4 POP PEEK PUSH 5

5 stack implementation import java.util.ArrayList; public class Stack { private ArrayList items; public Stack() { } public void push(T newItem) { } public void pop() { } public T peek() { } public int size() { } public boolean empty() { } recall that the ArrayList class provides member functions for all of these add remove get size we could simply use an ArrayList whenever we want stack behavior better yet, define a Stack class in terms of ArrayList

6 Name that code! Stack numStack = new Stack (); int num Integer.parseInt(JOptionPane.showInputDialog("Enter a number")); while (num > 0) { numStack.push(num); num = Integer.parseInt(JOptionPane.showInputDialog("Enter another number")); } while ( !numStack.empty() ) { System.out.println(numStack.peek()); numStack.pop(); } Stack numStack1 = new Stack (); Stack numStack2 = new Stack (); int num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number")); while (num > 0) { numStack1.push(num); num = Integer.parseInt(JOptionPane.showInputDialog("Enter another number")); } while ( !numStack1.empty() ) { numStack2.push(numStack1.peek()); numStack1.pop(); } while ( !numStack2.empty() ) { System.out.println(numStack2.peek()); numStack2.pop(); }

7 Stack class since a stack is a common data structure, a predefined Java class exists import java.util.Stack;  Stack is generic to allow any type of value to be stored Stack wordStack = new Stack (); Stack numStack = new Stack ();  the standard Stack class has all the same* methods as our implementation public T push(T item); // adds item to top of stack public T pop();// removes item at top of stack public T peek();// returns item at top of stack public boolean empty();// returns true if empty public int size();// returns size of stack

8 Stack application consider mathematical expressions such as the following  a compiler must verify such expressions are of the correct form (A * (B + C) )((A * (B + C)) + (D * E)) how do you make sure that parentheses match? common first answer:  count number of left and right parentheses  expression is OK if and only if # left = # right (A * B) + )C( more subtle but correct answer:  traverse expression from left to right  keep track of # of unmatched left parentheses  if count never becomes negative and ends at 0, then OK

9 Parenthesis matching public class ParenChecker { public static boolean match(String expr) { int openCount = 0; for (int i = 0; i < expr.length(); i++) { char ch = expr.charAt(i); if (ch == '(') { openCount++; } else if (ch == ')') { if (openCount > 0) { openCount--; } else { return false; } return (openCount == 0); } openCount keeps track of unmatched left parens as the code traverses the string, the counter is incremented on '(' decremented on ')' openCount must stay non- negative and end at 0

10 Delimiter matching now, let's generalize to multiple types of delimiters (A * [B + C] ){(A * [B + C]) + [D * E]} does a single counter work? recursive solution:  traverse the expression from left to right  if you find a left delimiter, recursively traverse until find the matching delimiter stack-based solution:  start with an empty stack of characters  traverse the expression from left to right if next character is a left delimiter, push onto the stack if next character is a right delimiter, must match the top of the stack how about separate counters for each type of delimiter?

11 Delimiter matching import java.util.Stack; public class DelimiterChecker { private String delimiters; public DelimiterChecker(String delims) { delimiters = delims; } public boolean check(String expr) { Stack delimStack = new Stack (); for (int i = 0; i < expr.length(); i++) { char ch = expr.charAt(i); if (isLeftDelimiter(ch)) { delimStack.push(ch); } else if (isRightDelimiter(ch)) { if (!delimStack.empty() && match(delimStack.peek(), ch)) { delimStack.pop(); } else { return false; } return delimStack.empty(); }... when you construct a DelimiterChecker, specify the delimiter pairs in a String DelimiterChecker simple = new DelimiterChecker("()"); DelimiterChecker messier = new DelimiterChecker("()[]{}<>");

12 Delimiter matching (cont.)... private boolean isLeftDelimiter(char ch) { int index = delimiters.indexOf(ch); return (index >= 0) && (index % 2 == 0); } private boolean isRightDelimiter(char ch) { int index = delimiters.indexOf(ch); return (index >= 0) && (index % 2 == 1); } private boolean match(char left, char right) { int indexLeft = delimiters.indexOf(left); int indexRight = delimiters.indexOf(right); return (indexLeft >= 0) && (indexLeft + 1 == indexRight); } private helper methods search the delimiters field to recognize and match delimiters left delimiters are in even numbered indices right delimiters are in odd numbered indices matching delimiters are consecutive

13 Reverse Polish evaluating Reverse Polish (postfix) expressions  note: if entering expressions into a calculator in postfix, don't need parens  this format was used by early HP calculators (& some models still allow the option)  *  (1 + 2) * * +  1 + (2 * 3) to evaluate a Reverse Polish expression:  start with an empty stack that can store numbers  traverse the expression from left to right  if next char is an operand (number or variable), push on the stack  if next char is an operator (+, -, *, /, …), 1.pop 2 operands off the top of the stack 2.apply the operator to the operands 3.push the result back onto the stack  when done, the value of the expression is on top of the stack

14 HW5 build upon existing classes to create an infix/postfix calculator Expression is an abstract class a class with some fields/methods defined, others left abstract similar to interface methods, abstract methods MUST be implemented by any derived class you are provided with an InfixExpression class, derived from Expression  implements abstract verify method to verify a valid infix expression  implements abstract evaluate method to evaluate an infix expression you will similarly implement a PostfixExpression class  implement abstract verify method to verify a valid postfix expression  implement abstract evaluate method to evaluate a postfix expression (using Stack)

15 Run-time stack when a method is called in Java (or any language):  suspend the current execution sequence  allocate space for parameters, locals, return value, …  transfer control to the new method when the method terminates:  deallocate parameters, locals, …  transfer control back to the calling point (& possibly return a value) note: methods are LIFO entities  main is called first, terminates last  if main calls foo and foo calls bar, then bar terminates before foo which terminates before main  a stack is a natural data structure for storing information about function calls and the state of the execution

16 Run-time stack (cont.) an activation record stores info (parameters, locals, …) for each invocation of a method  when the method is called, an activation record is pushed onto the stack  when the method terminates, its activation record is popped  note that the currently executing method is always at the top of the stack public static void main(String[] args) { int x = 12; foo(x); System.out.println("main " + x); } public static void foo(int a) { a++; System.out.println("foo " + a); } main: x = automatically start with main main: x = when foo called, push foo: a = main: x = when foo done, pop when main done, pop & end

17 Another example public static void main(String[] args) { int x = 12; foo(x); System.out.println("main1 " + x); bar(5); System.out.println("main2 " + x); } public static void foo(int a) { a++; System.out.println("foo " + a); bar(a + 10); } public static void bar(int x) { x--; System.out.println("bar " + x); } run time stack behavior?

18 Recursive example public static void main(String[] args) { int val = sum1toN(4) System.out.println("main " + val); } public static int sum1toN(int N) { if (N == 1) { return 1; } else { return sum1toN(N-1) + N; } recursive methods are treated just like any other methods  when a recursive call is made, an activation record for the new instance is pushed on the stack  when terminates (i.e., BASE CASE), pop off activation record & return value Recurse: N = 4... main: val = ?... Recurse: N = 3... Recurse: N = 2... Recurse: N = 1... returns 1returns 1+2 = 3returns 3+3 = 6returns 6+4 = 10 displays "main 10"

19 Programming language implementation note: method calls are not the only predictable (LIFO) type of memory  blocks behave like unnamed methods, each is its own environment for (int i = 0; i < 10; i++) { int sum = 0; if (i % 3 == 0) { int x = i*i*i; sum = sum + x; } even within a method or block, variables can be treated as LIFO int x;... int y; for most programming languages, predictable (LIFO) memory is allocated/deallocated/accessed on a run-time stack