CSE 214 – Computer Science II Stack Applications

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Stacks.
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.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks, Queues, and Deques
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Introduction to Stacks What are Stacks? Stack implementation using arrays. Stack application.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
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.
30-Jun-15 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.
Topic 3 The Stack ADT.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
Data Structures and Algorithms
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.
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.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
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 and Queues Pepper. Why History Simplicity Operating Systems – Function Call Stack.
Stacks  Introduction  Applications  Implementations  Complex Applications.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Lecture objectives  Collections interface  Learn about stacks and their methods:  push  pop  peek  Empty  Analyze stack applications and why stacks.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
Object-Oriented Programming Simple Stack Implementation.
Lecture6: Stacks Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Data Structures & Algorithms
Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
CSC 205 – Java Programming II Lecture 30 April 3, 2002.
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
Click to edit Master text styles Stacks Data Structure.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stack: Last In First Out (LIFO).–Used in procedure calls, to compute arithmetic expressions.
Stacks (and Queues).
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
MIDTERM OCTOBER 17 IN LAB Chapter 3 Stacks.
Revised based on textbook author’s notes.
COMPSCI 107 Computer Science Fundamentals
2.5 Another Java Application: Adding Integers
Stacks.
Stacks Chapter 7 introduces the stack data type.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
COMPUTER 2430 Object Oriented Programming and Data Structures I
CS Week 6 Jim Williams, PhD.
CSC 205 – Java Programming II
Stacks Chapter 5 Adapted from Pearson Education, Inc.
MIDTERM OCTOBER 11 IN LAB Chapter 3 Stacks.
An Introduction to Java – Part I, language basics
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
Stacks.
Stacks.
Topic 15 Implementing and Using Stacks
Stacks Chapter 5.
Stack.
Stacks.
Corresponds with Chapter 5
A type is a collection of values
Presentation transcript:

CSE 214 – Computer Science II Stack Applications Source: http://www.telusplanet.net/public/millsy/Games_win2k3.jpg

Why are stacks useful? They are good for solving particular types of problems 2 will look at today: the call stack evaluating arithmetic expressions

The Call Stack The Java Virtual Machine manages a Call Stack one for each thread actually When a method is called, a frame object is pushed onto that that thread’s Call Stack When a method returns, the top method is popped off that thread’s Call Stack

What’s a frame? Also called an activation record Has data for method call local variables & arguments Ex: public static void dummy(int num) { int sqr = num * num; String s = "sqr: "; printStuff(s + sqr); } dummy num (32 bits) s (32 bits) sqr (32 bits) s + sqr (32 bits)

Call Stack Example public static void main(String[] args) { int num1 = 5; dummy(num1); } public static void dummy(int num2) int sqr = num * num; String s = "sqr: "; printStuff(s + sqr); public static void printStuff(String n) System.out.println(n); main args num1 dummy num2 sqr s s + sqr printStuff n

Solve the following Now, let’s write a method that could solve this (((6 + 9)/3)*(6-4)) =((15/3)*(6-4)) =(5 * (6-4)) =(5 * 2) =10 Now, let’s write a method that could solve this Ex: int solveEquation(String equation) { …

How can we solve this? Using 2 steps 1st step: are parentheses balanced? if no, throw exception if yes, continue 2nd step: evaluate expression

public static int solveEquation(String equation) throws UnbalancedParenthesisException { if (areParenthesesBalanced(equation)) return evaluateExpression(equation); else throw new UnbalancedParenthesisException( "Unbalanced Parenthesis"); }

boolean areParenthesesBalanced(String exp) What should be the following output? String s1 = "(6 + 9)"; String s2 = "(6 + "; String s3 = "(6 + 9))"; boolean result; result = areParenthesesBalanced (s1); System.out.println(s1 + " is balanced: " + result + "\n"); result = areParenthesesBalanced (s2); System.out.println(s2 + " is balanced: " + result + "\n"); result = areParenthesesBalanced (s3); System.out.println(s3 + " is balanced: " + result); (6 + 9) is balanced: true (6 + is balanced: false (6 + 9)) is balanced: false

areParenthesesBalanced Let’s use a Stack to solve this problem How? examine all characters in expression, left to right if you find a ‘(‘, push it on the stack if you find a ‘)’, pop the stack If stack was empty, return 0 when done, if you have an empty stack, return 1 else return 0

public static boolean areParenthesesBalanced(String exp) { Stack<Character> stack = new Stack<Character>(); int i; boolean areBalanced; Object poppedData = null; char charToAdd; for (i = 0; i < exp.length(); i++) if (exp.charAt(i) == '(') stack.push('('); else if (exp.charAt(i) == ')') try{ poppedData = stack.pop(); } catch(EmptyStackException ese) return false; }

try { poppedData = stack try { poppedData = stack.pop(); return false; } catch(EmptyStackException ese) return true;

2nd step: evaluate expression How? Use 2 Stacks one for operators (+, -, *, /, etc.) one for operands (5, 6.2, etc.) Examine each character in the expression, left to right

Assumptions Fully parenthesized equations No foreign characters in expression to screw up number parsing let’s keep it simple Fully parenthesized equations matching ‘)’ for each operator this is ok: ((5 + (2 + 3))/10) this is not ok: (5 + (2 + 3)/10) Note: this is not the most robust approach in the world

Expression Examination When we find a: ‘(’ or ‘ ‘, do nothing ‘+’, ‘-’, ‘/’, or ‘*’, add it to the operator stack number, add it to the operand stack ‘)’: pop top operator pop top two operands evaluate expression using this data what do we do with the result? if we are at end of expression, return result else add result to operand stack

int evaluateExpression(String exp) What should be the following output? String e1 = "(((6 + 9)/3)*(6-4))"; String e2 = "(2 * (1024 / 16))"; String e3 = "((10 + ((100 * ((5 + 1) * (20 / (2 * 5)))) + (10 + 5)))/10)"; int num; num = evaluateExpression(e1); System.out.println(e1 + " = " + num); num = evaluateExpression(e2); System.out.println(e2 + " = " + num); num = evaluateExpression(e3); System.out.println(e3 + " = " + num); (((6 + 9)/3)*(6-4)) = 10 (6 / 3) = 2 ((10 + ((100 * ((5 + 1) * (20 / (2 * 5)))) + (10 + 5)))/10) = 122

public static int evaluateExpression(String exp) { Stack<Character> operators = new Stack<Character>(); Stack<Integer> operands = new Stack<Integer>(); int result, i; result = 0; for (i = 0; i < exp.length(); i++) char c = exp.charAt(i); if ((c == '(') || (c == ' ')) ; // DO NOTHING else if ((c == '+') || (c == '-') || (c == '*') || (c == '/')) operators.push(c);

else if (c == ')') { int operand1 = operands else if (c == ')') { int operand1 = operands.pop(); int operand2 = operands.pop(); char operator = operators.pop(); if (operator == '+') result = operand2 + operand1; else if (operator == '-') result = operand2 - operand1; else if (operator == '*') result = operand2 * operand1; else result = operand2 / operand1; if (i < (exp.length()-1)) operands.push(result); }

else { int j = i; while (Character. isDigit(exp else { int j = i; while (Character.isDigit(exp.charAt(j))) j++; String sub = exp.substring(i,j); int operandToAdd = Integer.parseInt(sub); operands.push(operandToAdd); i = j-1; } return result;

Other Stack Uses To Help Validate Source Code To Help Validate HTML match all parentheses, ( & ) match all brackets, { & } To Help Validate HTML match all < & > match all tags, i.e. <li> & </li>