CS 171: Introduction to Computer Science II. Stacks. Li Xiong

Similar documents
09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

Stack Abstract Data Type

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

CS W3134: Data Structures in Java

March 13/2003 Jayakanth Srinivasan,

STACKS AND QUEUES. Problem Solving with Computers-II

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

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

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

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques

CS2383 Programming Assignment 3

Stacks. Revised based on textbook author s notes.

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

The Stack and Queue Types

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Programming Abstractions

Stack and Its Implementation

Stacks Fall 2018 Margaret Reid-Miller

Formal Languages and Automata Theory, SS Project (due Week 14)

CS 206 Introduction to Computer Science II

15. Stacks and Queues

Lecture 12 ADTs and Stacks

Types of Data Structures

Top of the Stack. Stack ADT

CS 206 Introduction to Computer Science II

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

Data Structures and Algorithms

Review: Expressions, Variables, Loops, and more.

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

Lecture Chapter 6 Recursion as a Problem Solving Technique

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.

[CS302-Data Structures] Homework 2: Stacks

Stacks and their Applications

ABSTRACT DATA TYPES (ADTS) COMP1927 Computing 2 16x1 Sedgewick Chapter 4

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack.

Top of the Stack. Stack ADT

CSC 222: Computer Programming II. Spring 2005

BBM 201 DATA STRUCTURES

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Chapter 04: Instruction Sets and the Processor organizations. Lesson 18: Stack-based processor Organisation

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

BBM 201 DATA STRUCTURES

Lab 7 1 Due Thu., 6 Apr. 2017

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Stacks and Queues. Stack - Abstract Data Type. Stack Applications. Stack - Abstract Data Type - C Interface

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Assessment of Programming Skills of First Year CS Students: Problem Set

Programming Abstractions

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Programming Abstractions

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Problem with Scanning an Infix Expression

Application of Stack (Backtracking)

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Lecture Data Structure Stack

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

Lecture 4 Stack and Queue

Infix to Postfix Conversion

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

Stacks II. Adventures in Notation. stacks2 1

An Introduction to Trees

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Data Structures and Algorithms

PA3 Design Specification

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Stacks, Queues and Hierarchical Collections

Linear Data Structure

Prefix/Infix/Postfix Notation

Postfix (and prefix) notation

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS THE STACK

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

Data Structure. Recitation IV

Stating the obvious, people and computers do not speak the same language.

Stacks, Queues (cont d)

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Introduction to Programming (Java) 4/12

12 Abstract Data Types

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

CDA 3103 Computer Organization Homework #7 Solution Set

Topics. Computer Organization CS Exam 2 Review. Infix Notation. Reverse Polish Notation (RPN)

CSC 222: Computer Programming II. Spring 2004

CISC-235. At this point we fnally turned our atention to a data structure: the stack

Stacks Stack Examples:

Stacks Calculator Application. Alexandra Stefan

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Monday, November 13, 2017

Data Structures Week #3. Stacks

CSC 273 Data Structures

Transcription:

CS 171: Introduction to Computer Science II Stacks Li Xiong

Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching Application 3: Expression evaluation Hw2: N-Queens problem

Application 2 Delimiter Matching Check if the parentheses in an mathematical expression is balanced: (w * (x + y) / z (p / (r q) ) ) It may have several different types of delimiters: braces}, brackets[], parentheses(). Each opening on the left delimiter must be matched by a closing (right) delimiter. Left delimiters that occur later should be closed before those occurring earlier. 9/24/2012 3

Application 2 Delimiter Matching Examples: 9/24/2012 4

Application 2 Delimiter Matching Examples: 9/24/2012 5

Application 2 Delimiter Matching Use a stack: Read characters from the string. Whenever you see a left (opening) delimiter, push it to the stack. Whenever you see a right (closing) delimiter, pop the opening delimiter from the stack and match. What are the error conditions? 9/24/2012 6

Application 2 Delimiter Matching Use a stack: Read characters from the string. Whenever you see a left (opening) delimiter, push it to the stack. Whenever you see a right (closing) delimiter, pops the opening delimiter from the stack and match. If they don t match, matching error. If stack is empty when you try to match a closing delimiter, missing left delimiter error If the stack is non-empty after all characters are Processed, missing right delimiter error 9/24/2012 7

Application 2 Delimiter Matching Program: ~cs171000/share/code/brackets Why does this work? Delimiters that are opened last must be closed first. This conforms exactly with the LIFO property of the stack. 9/24/2012 8

public void check() int stacksize = input.length(); // get max stack size StackX thestack = new StackX(stackSize); // make stack for(int j=0; j<input.length(); j++) // get chars in turn char ch = input.charat(j); // get char switch(ch) case '': // opening symbols case '[': case '(': thestack.push(ch); // push them break; case '}': // closing symbols case ']': case ')': if(!thestack.isempty() ) // if stack not empty, char chx = thestack.pop(); // pop and check if( (ch=='}' && chx!='') (ch==']' && chx!='[') (ch==')' && chx!='(') ) System.out.println("Error: "+ch+" at "+j); } else // prematurely empty System.out.println("Error: "+ch+" at "+j); break; default: // no action on other characters break; } // end switch } // end for // at this point, all characters have been processed if(!thestack.isempty() ) System.out.println("Error: missing right delimiter"); } // end check()

public void check() int stacksize = input.length(); // get max stack size StackX thestack = new StackX(stackSize); // make stack for(int j=0; j<input.length(); j++) // get chars in turn char ch = input.charat(j); // get char switch(ch) case '': // opening symbols case '[': case '(': thestack.push(ch); // push them break; case '}': // closing symbols case ']': case ')': if(!thestack.isempty() ) // if stack not empty, char chx = thestack.pop(); // pop and check if( (ch=='}' && chx!='') (ch==']' && chx!='[') (ch==')' && chx!='(') ) System.out.println("Error: "+ch+" at "+j); } else // prematurely empty System.out.println("Error: "+ch+" at "+j); break; default: // no action on other characters break; } // end switch } // end for // at this point, all characters have been processed if(!thestack.isempty() ) System.out.println("Error: missing right delimiter"); } // end check()

public void check() int stacksize = input.length(); // get max stack size StackX thestack = new StackX(stackSize); // make stack for(int j=0; j<input.length(); j++) // get chars in turn char ch = input.charat(j); // get char switch(ch) case '': // opening symbols case '[': case '(': thestack.push(ch); // push them break; case '}': // closing symbols case ']': case ')': if(!thestack.isempty() ) // if stack not empty, char chx = thestack.pop(); // pop and check if( (ch=='}' && chx!='') (ch==']' && chx!='[') (ch==')' && chx!='(') ) System.out.println("Error: "+ch+" at "+j); } else // prematurely empty System.out.println("Error: "+ch+" at "+j); break; default: // no action on other characters break; } // end switch } // end for // at this point, all characters have been processed if(!thestack.isempty() ) System.out.println("Error: missing right delimiter"); } // end check()

public void check() int stacksize = input.length(); // get max stack size StackX thestack = new StackX(stackSize); // make stack for(int j=0; j<input.length(); j++) // get chars in turn char ch = input.charat(j); // get char switch(ch) case '': // opening symbols case '[': case '(': thestack.push(ch); // push them break; case '}': // closing symbols case ']': case ')': if(!thestack.isempty() ) // if stack not empty, char chx = thestack.pop(); // pop and check if( (ch=='}' && chx!='') (ch==']' && chx!='[') (ch==')' && chx!='(') ) System.out.println("Error: "+ch+" at "+j); } else // prematurely empty System.out.println("Error: "+ch+" at "+j); break; default: // no action on other characters break; } // end switch } // end for // at this point, all characters have been processed if(!thestack.isempty() ) System.out.println("Error: missing right delimiter"); } // end check()

Application 3 Arithmetic Expression Evaluation Task: evaluate arithmetic expressions. Familiar arithmetic expressions: 2+3 2+(3+4) (1 + ( (2 + 3) * (4 * 5) ) ) The operators are placed between two operands. This is called infix notation. 9/24/2012 13

Application 3 Arithmetic Expression Evaluation Program: http://algs4.cs.princeton.edu/13stacks/evaluate.java.html Demo: http://algs4.cs.princeton.edu/lectures/13demodijkstratwostack.mov

Postfix (RPN) Notation For computers to parse the expressions, it s more convenient to represent expressions in postfix notation, also known as reverse polish notation (RPN) Operators are placed after operands. 23+ AB/ Postfix notation is parenthesis-free as long all operators have fixed # operands 9/24/2012 16

Evaluating Postfix Expressions Example: 345+*612+/- This is equivalent to the infix expression: 3*(4+5) - 6 / (1+2) How do we evaluate this postfix expression? 9/24/2012 17

Implementation Idea Whenever we encounter an operator, we apply it to the last two operands we ve seen. 345+*612+/- 9/24/2012 18

Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching Application 3: Expression evaluation Hw2: N-Queens problem

Hw2 N-Queens Problem Place N queens on a NxN chess board such that no two queens attack each other. No two queens share the same row, column, or diagonal A search problem

Brute-force Search Generate and test: enumerate all possible candidates and check whether it satisfies the constraint If we know N ahead of time (say, N=4), we can use an N-nested loop (enforcing one queen in each row) for (int i=0; i<n; i++) for (int j=0; j<n; j++) for (int k=0; k<n; k++) for (int m=0; m<n; m++) // check validity of (i,j,k,m) } } } }

Backtracking For each row, place a queen in first valid position, then move to next row If there is no valid position, then backtrack to previous row and try next position If you successfully place a queen in the last row, then a solution is found, backtrack to find next solution

Using Stack for Backtracking Use Stack to keep track of current column positions in each row If you find a valid position in current row, push to the stack and start on next row If there is no valid position in current row, backtrack to previous row - pop the position of previous row from the stack and search for valid position further down the row Example stack for 4-queens When is a solution found? When should the search stop?

Algorithm Create empty stack and set current position to 0 Repeat loop from current position to the last position until a valid position is found //current row if there is a valid position push the position to stack, set current position to 0 // move to next row } if there is no valid position if stack is empty, break // stop search else pop from stack, set current position to next position // backtracking to previous row } if stack has size N // a solution is found pop from stack, set current position to next position // backtracking to find next solution } }

Check for Valid Position Implement a method for checking if a position is valid given the positions in previous rows Need to iterate through all existing positions stored in the stack Use Stack s get(int index) method (Java s stack class provides indexed access) (Can also use Stack s iterator, discussed later in class) Need to check column conflict and diagonal conflict (both major and minor diagonal)