More Linear Data Structures

Similar documents
Introduction to Stacks

Data Structures and Algorithms V Otávio Braga

Module 2 Stacks and Queues: Abstract Data Types

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

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!

7.1 Our Current Model

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

DATA STRUCTURES USING C

Chapter 3: Restricted Structures Page 1

Algorithms and Data Structures

Stacks. Data Structures and Data Types. Collections

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

14 Stacks, Queues, And Linked Lists

CompSci-61B, Data Structures Final Exam

Common Data Structures

CmpSci 187: Programming with Data Structures Spring 2015

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

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

D06 PROGRAMMING with JAVA

PES Institute of Technology-BSC QUESTION BANK

Semantic Analysis: Types and Type Checking

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

Linked Lists Linked Lists, Queues, and Stacks

Data Structures and Algorithms Stacks and Queues

10CS35: Data Structures Using C

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

Data Structure [Question Bank]

Analysis of a Search Algorithm

DATA STRUCTURE - STACK

STACKS,QUEUES, AND LINKED LISTS

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

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

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

HW3: Programming with stacks

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

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

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

2) Write in detail the issues in the design of code generator.

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

Chapter 5 Instructor's Manual

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

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

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

Moving from CS 61A Scheme to CS 61B Java

Programming with Data Structures

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

Stack Allocation. Run-Time Data Structures. Static Structures

Introduction to Data Structures

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

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

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Stacks. Linear data structures

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

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

Java Software Structures

Universidad Carlos III de Madrid

Bottom-Up Parsing. An Introductory Example

Data Structures UNIT III. Model Question Answer

Data Structures and Algorithms Lists

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

Abstract Data Types. Chapter 2

Computational Mathematics with Python

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Lecture 12 Doubly Linked Lists (with Recursion)

COMPUTER SCIENCE. Paper 1 (THEORY)

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

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

Lecture 9. Semantic Analysis Scoping and Symbol Table

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Computational Mathematics with Python

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

C++ INTERVIEW QUESTIONS

Class 32: The Java Collections Framework

C Compiler Targeting the Java Virtual Machine

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Programming Languages CIS 443

Java Interview Questions and Answers

Computing Concepts with Java Essentials

CMSC 202H. ArrayList, Multidimensional Arrays

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

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

Lecture J - Exceptions

The previous chapter provided a definition of the semantics of a programming

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

Data Structures. Level 6 C Module Descriptor

Object Oriented Software Design

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

PSTricks. pst-ode. A PSTricks package for solving initial value problems for sets of Ordinary Differential Equations (ODE), v0.7.

Inside the Java Virtual Machine

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: )

Datastrukturer och standardalgoritmer i Java

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

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

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

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

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Transcription:

More Linear Data Structures 3A Stacks 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 1 Stacks 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 2 1

Stack Operations public interface LIFOStack<E> { public void push(e element); // Insert element at top of stack public boolean isempty(); // Is the stack empty? public E pop(); // Remove element from top of stack public E peek(); // Examine element at top of stack 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 3 Stacks using an array 0 1 2 3 4 5 6 7 8 9 10 11 Store the elements of the stack from top to bottom in order in the array. Which end should be the top of the stack? Why? 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 4 2

Array Implementation Fields public class ArrayStack<E> implements LIFOStack<E> { private E[] dataarray; private int top; // methods (next slides) index of top stack element in array 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 5 Array Implementation Constructor & isempty public ArrayStack<E>() { dataarray = (E[])new Object[1]; top = -1; public boolean isempty() { return (top == -1); indicates an empty stack 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 6 3

Array Implementation push public void push(e element) { if ( ) reallocate(); // not shown top = top + 1; dataarray[top] = element; 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 7 Array Implementation pop public E pop() { if ( ) throw new NoSuchElementException(); E element = dataarray[top]; top = top - 1; return element; 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 8 4

Array Implementation peek public E peek() { if ( ) throw new NoSuchElementException(); return dataarray[top]; 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 9 Stacks using a singly-linked list head null Store the elements of the stack from top to bottom in order in the list. Which end should be the top of the stack? Why? 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 10 5

Linked List Implementation Fields public class ListStack<E> implements LIFOStack<E> { private Node<E> top; // methods (next slides) reference to node with top stack element in list 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 11 Linked List Implementation Constructor & isempty public ListStack<E>() { top = null; indicates an empty stack public boolean isempty() { return (top == null); 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 12 6

Linked List Implementation push public void push(e element) { Node<E> newnode = new Node<E>(element); newnode.next = top; top = newnode; null top newnode null 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 13 Linked List Implementation pop public E pop() { if (top == null) throw new NoSuchElementException(); E element = top.data; top = top.next; return element; data null top element data 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 14 7

Linked List Implementation peek public E peek() { if (top == null) throw new NoSuchElementException(); return top.data; 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 15 Nested Parentheses Determine if a string containing a mathematical expression is nested correctly. Parenthetical symbols include {, [ ], ( ). Algorithm: Process the expression from left to right. Push each left parenthetical symbol on a stack. When you encounter a right parenthetical symbol, pop the stack to see if there is a matching left parenthetical symbol. If not, the parenthetical nesting is invalid. After the entire expression is processed, if the stack is empty, the parenthetical nesting is valid. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 16 8

Examples { [ ( ) ] { ( [ [ [ { { { { { { { { [ { ( ) ] { ( { { ERROR: ( doesn t match with [ [ [ [ 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 17 RPN (Postfix Notation) Some modern calculators use Reverse Polish Notation (RPN) Developed in 1920 by Jan Lukasiewicz Computation of mathematical formulas can be done without using any parentheses Example: 5 * ( 6 + 7 ) becomes in RPN: 5 6 7 + * Hewlett-Packard 35s scientific calculator Hewlett-Packard 12c financial calculator 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 18 9

Evaluating postfix with a stack NOTE: Assume the postfix expression is valid. 1. Let each entry in a postfix expression be a token. 2. Let S be an empty stack. 3. For each token in the expression: a. If the token is a number, push it on stack S. b. Otherwise (the token is an operator): i. Pop a token off stack S and store it in y. ii. Pop a token off stack S and store it in x. iii. Evaluate: x operator y. iv. Push result on stack S. 4. Pop the stack for the final answer. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 19 Evaluating postfix: Example Postfix (RPN): 5 7 + 8 6 - / 3 9 * + 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 20 10

Converting Infix to Postfix NOTE: Assume the infix expression is valid. 1. Let each entry in an infix expression be a token. 2. Let S be an empty stack. 3. Let postfix be an empty string. 4. For each token in the infix expression: a. If the token is a number, append it to the postfix string. b. Otherwise (the token is an operator), process the operator (see next 2 slides) 5. While the stack S is not empty: a. Pop an operator off of stack S and append it to the postfix string. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 21 Processing the operators (Converting infix to postifix, cont'd) Each operator has a precedence. *, / multiplicative higher precedence +, - additive lower precedence Operators of the same precedence are evaluated left to right. Operator Precedence Assign precedence values * 2 to each operator: / 2 + 1-1 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 22 11

Process the operator (Converting infix to postifix, cont'd) 1. Let nextop represent the operator token. 2. If stack S is empty, push nextop on stack S. 3. Otherwise: a. Let topop = peek(s). b. If prec(nextop) > prec(topop), push nextop on stack S. c. Otherwise: i. While S is not empty and prec(nextop) prec(topop): a) Let topop = pop(s). b) Append topop to postfix string. c) If stack S is not empty, let topop = peek(s). ii. Push nextop on stack S. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 23 Converting: An example Infix: 5 + 4 * 3 / 2-1 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 24 12

Processing the operators (Converting infix to postifix, cont'd) What if the infix expression contains parentheses? Each pair of parentheses marks a subexpression that must be completely converted before previous operators are processed. Assign a very low precedence to left and right parentheses so only a right parenthesis can pop off a left parenthesis. Do not put parentheses in the postfix string. Operator Precedence * 2 / 2 + 1-1 ( -1 ) -1 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 25 Process the operator - revised (Converting infix to postifix, cont'd) 1. Let nextop represent the current operator token. 2. If stack S is empty or nextop is '(', push nextop on stack S. 3. Otherwise: a. Let topop = peek(s). b. If prec(nextop) > prec(topop), push nextop on stack S. c. Otherwise: i. While S is not empty and prec(nextop) prec(topop): a) Let topop = pop(s). b) If topop is '(', exit loop immediately. c) Append topop to postfix string. d) If stack S is not empty, let topop = peek(s). ii. If nextop is not ')', push nextop on stack S. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 26 13

Converting: An example Infix: 7 + 5 * ( 4 / 2 + 1 ) - 6 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 27 Invalid expressions Assume that tokens are only operators and integers. Evaluating a postfix expression: How would you know that the postfix expression was not valid? Converting an infix expression to postfix: How would you know that the initial infix expression was not valid? 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 28 14

Run-Time Stack & Activation Frames Java maintains a run-time stack during the execution of your program. Each call to a method generates an activation frame that includes storage for: arguments to the method local variables for the method return address of the instruction that called the method A call to a method pushes an activation record on the run-time stack. A return from a method pops an activation record from the run-time stack. 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 29 Run-Time Stack & Activation Frames System.out.println(A(3)); public int A(int w) { int x = B(w+1); return x*4; public int B(int x) { int y = C(x+1, x+2); return y*3; public int C(int y1, int y2) { int z = y1 + y2; return z*2; ret addr z y2 6 y1 5 ret addr y x 4 Activation record for method C Activation record for method B ret addr Activation x record for method A w 3 rest of run-time stack 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 30 15

Other uses for stacks Computing a convex hull Backtracking through a problem space (e.g. maze) Parsing algorithms in a compiler Machine language architecture Java Virtual Machine 15-121 Introduction to Data Structures, Carnegie Mellon University - CORTINA 31 16