4.3 Stacks and Queues. Pushdown Stacks. Data Structures and Data Types. Collections

Similar documents
Stacks. Data Structures and Data Types. Collections

Collaboration policy. Where to get help (but no code in ) Office hours Lab TAs in Friend 008/009 Bounce ideas (but not code) off classmates

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

DATA STRUCTURES USING C

Chapter 3: Restricted Structures Page 1

Algorithms and Data Structures

Common Data Structures

7.1 Our Current Model

Lecture 15: Linked Structures

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

10CS35: Data Structures Using C

Introduction to Stacks

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

Data Structures and Algorithms V Otávio Braga

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

Data Structure [Question Bank]

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

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

Moving from CS 61A Scheme to CS 61B Java

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

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

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

Introduction to Data Structures

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

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

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

PES Institute of Technology-BSC QUESTION BANK

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!

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

cs2010: algorithms and data structures

Analysis of a Search Algorithm

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

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 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

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

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

STACKS,QUEUES, AND LINKED LISTS

Advanced Computer Architecture-CS501. Computer Systems Design and Architecture 2.1, 2.2, 3.2

D06 PROGRAMMING with JAVA

Object Oriented Software Design

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Stacks. Linear data structures

Introduction to Java

Object Oriented Software Design

Practical Session 4 Java Collections

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

The C Programming Language course syllabus associate level

Java Basics: Data Types, Variables, and Loops

Stack Allocation. Run-Time Data Structures. Static Structures

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

Java Application Developer Certificate Program Competencies

Data Structures and Data Manipulation

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 5 Instructor's Manual

CmpSci 187: Programming with Data Structures Spring 2015

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

DATA STRUCTURE - STACK

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

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

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

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

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the 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.

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

LINKED DATA STRUCTURES

Sequential Data Structures

ProfBuilder: A Package for Rapidly Building Java Execution Profilers Brian F. Cooper, Han B. Lee, and Benjamin G. Zorn

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

Data Structures and Algorithms Stacks and Queues

Linked Lists Linked Lists, Queues, and Stacks

AP Computer Science Java Subset

Computer Programming I

Algorithms and Data Structures

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

Chapter 5 Names, Bindings, Type Checking, and Scopes

Java the UML Way: Integrating Object-Oriented Design and Programming

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Introduction to Programming

Universidad Carlos III de Madrid

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

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

Java Interview Questions and Answers

Data Structures. Level 6 C Module Descriptor

Chapter 2: Elements of Java

Introduction to Programming System Design. CSCI 455x (4 Units)

HW3: Programming with stacks

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

CompSci-61B, Data Structures Final Exam

14 Stacks, Queues, And Linked Lists

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:

Software Engineering Techniques

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

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

Transcription:

Data Structures and Data Types 4.3 Stacks and Queues Data types Set values. Set operations on those values. Some are built in to Java: int, double, char,... Most are not: Complex, Picture, Charge, Stack, Queue, Graph,... Data structures. Represent data. Represent relationships among data. Some are built in to Java: arrays, String,... Most are not: linked list, circular list, tree, sparse array, graph,... this lecture TSP next lecture this lecture Design challenge for every data type: What data structure to use? Requirement 1: Space usage. Requirement 2: Time usage for datatype methods 2 Collections Fundamental data types. Set operations (add, remove, test if empty) on generic data. Intent is clear when we insert. Which item do we remove? Pushdown Stacks Stack. (this lecture) Remove the item most recently added. Ex: cafeteria trays, Web surfing. Queue. (see text) Remove the item least recently added. Ex: Registrar's line. LIFO = "last in out" FIFO = " in out" Symbol Table. (next lecture) Remove item with a given key. Ex: Phone book 3 4

Stack API Stack Client Example 1: Reverse public class Reverse public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); stack.(stdin.readstring()); while (!stack.isempty()) StdOut.print(stack.()); StdOut.println(); % more tiny.txt it was the best times best the was times best the was best the was best the was times best the stack contents when StdIn is empty % java Reverse tiny.txt times it it it it was it 5 6 Stack Client Example 2: Test Client public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); String item = StdIn.readString(); if (item.compareto("")!= 0) stack.(item); else System.out.print(stack.()); System.out.println(); % more test.txt to be or not to be that is Stack Client Example 3: Balanced Parentheses ( ( ( a + b ) * d ) + ( e * f ) ) ( ) ( ) ( ) ( ) to not or % java StackOfStrings < test.txt to be not that or be stack contents just before () operation be to 7 8

Stack Client Example 3: Balanced Parentheses Stack: Array Implementation public class Balanced public static void main(string[] args) StackOfStrings stack = new StackOfStrings(); String item = StdIn.readString(); if (item.compareto("(") == 0) stack.(item); if (item.compareto(")") == 0) if (stack.isempty()) StdOut.println( Not balanced ); return; stack.(); if (!stack.isempty()) StdOut.println( Not balanced ); else StdOut.println( Balanced ); % java Balanced ( ( ( a + b ) * d ) + ( e * f ) ) Balanced % java Balanced ( ( a + b ) * d ) + ( e * f ) ) Not balanced Array implementation a stack. Use array a[] to store N items on stack. () add new item at a[n]. () remove item from a[n1]. public class ArrayStackOfStrings private String[] a; private int N = 0; public ArrayStackOfStrings(int max) a = new String[max]; public boolean isempty() return (N == 0); public void (String item) a[n++] = item; public String () return a[n]; PROBLEM: How big to make array? (Stay tuned.) Temporary solution: Make client provide capacity. not or stack contents after 4th () operation be to N to be or not a[0] a[1] a[2] a[3] 9 10 Array Stack: Trace TEQ on Stacks Q. Can we always insert commands () to make strings come out sorted? Ex 1: 6 5 4 3 2 1 Ex 2: 1 2 3 4 5 6 Ex 3: 4 1 3 2 6 5 11 12

Array Stack: Performance Running time. Push and take constant time.! Linked Lists Memory. Proportional to clientsupplied capacity, not number items. " Problem. API does not call for capacity (never good to change API) Client might have multiple stacks Client might not know what capacity to use (depends on its client) Challenge. Stack implementation where space use is not fixed ahead time. 13 14 Sequential vs. Linked Data Structures Singlylinked data structures Sequential data structure. Put object one next to another. TOY: consecutive memory cells. Java: array objects. From the point view a particular object, all these structures look the same: Sequential list (this lecture) Rho Linked data structure. Include in each object a link to the another one. TOY: link is memory address next object. Java: link is reference to next object. addr value addr C0 "Alice" C0 value "Carol" Circular list (TSP) Tree Key distinctions. get i th element Array: arbitrary access, fixed size. Linked list: sequential access, variable size. get next element C1 C2 C3 C4 C5 C6 C7 "Bob" "Carol" C1 C2 C3 C4 C5 C6 C7 null "Alice" CA General case C8 C8 Linked structures. Not intuitive, overlooked by naive programmers Flexible, widely used method for organizing data C9 CA CB array C9 CA "Bob" CB C0 linked list 15 Multiply linked structures: many more possibilities! 16

Linked Lists Building a Linked List Linked list. Simplest linked structure. A recursive data structure. A item plus a pointer to another linked list (or empty list). Unwind recursion: linked list is a sequence items. Node data type. A reference to a String. A reference to another Node. public class Node private String item; private Node next; Confusing point: Purpose data structure is to represent data in a data type but, we also use data types to implement data structures Node third = new Node(); third.item = "Carol"; third.next = null; Node second = new Node(); second.item = "Bob"; second.next = third; Node = new Node();.item = "Alice";.next = second; second second third third C4 CA C0 addr C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC Value "Carol" null "Alice" CA "Bob" C0 Alice Bob Carol item next special pointer value null terminates list Alice Bob item next Carol null CD CE CF main memory 17 18 Stack Push: Linked List Implementation Stack Pop: Linked List Implementation "" item =.item; second second = ; second =.next; garbagecollected = new Node(); second return item;.item = item;.next = second; 19 20

Stack: Linked List Implementation Linked List Stack: Trace public class LinkedStackOfStrings private Node = null; private class Node private String item; private Node next; not or be stack contents after 4th () operation in test client public boolean isempty() return == null; to public void (String item) Node second = ; = new Node();.item = item;.next = second; not or public String () String item =.item; =.next; return item; be Note difference between and second: : an instance variable that retains state second: a local variable that goes out scope to 21 22 LinkedList Stack: Performance Stack Data Structures: Tradefs Running time. Push and take constant time.! Two data structures to implement the Stack data type. Memory. Always proportional to number items in stack.! Array. Every / operation take constant time. But must fix maximum capacity stack ahead time. Linked list. Every / operation takes constant time. But uses extra space and time to deal with references. Client can evaluate performance tradefs to choose among implementations (implicitly choosing among underlying data structures) 23 24

TEQ on List Processing 1 TEQ on List Processing 2 What does the following code do? What does the following code do?... Node list = null; Node old = list; list = new Node(); list.item = StdIn.readString(); list.next = old; for (Node t = list; t!= null; t = t.next) StdOut.println(t.item);...... Node list = new Node(); list.item = StdIn.readString(); Node last = list; last.next = new Node(); last = last.next;; last.item = StdIn.readString();... 25 26 Parameterized Data Types Parameterized Data Types We implemented: StackOfStrings. We also want: StackOfMemoryBlocks, StackOfURLs, StackOfInts, Strawman. Implement a separate stack class for each type. Rewriting code is tedious and errorprone. Maintaining cutandpasted code is tedious and errorprone. 27 28

Generics Generics. Parameterize stack by a single type. String stack (for reference) Generic Stack: Linked List Implementation public class LinkedStackOfStrings private Node = null; public class Stack<Item> private Node = null; Stack Apples parameterized type private class Node private String item; private Node next; private class Node private Item item; private Node next; parameterized type name chosen by programmer Stack<Apple> stack = new Stack<Apple>(); Apple a = new Apple(); Orange b = new Orange(); stack.(a); stack.(b); // compiletime error a = stack.(); sample client Can t an Orange onto a Stack Apples public boolean isempty() return == null; public void (String item) Node second = ; = new Node();.item = item;.next = second; public boolean isempty() return == null; public void (Item item) Node second = ; = new Node();.item = item;.next = second; 29 public String () String item =.item; =.next; return item; public Item () Item item =.item; =.next; return item; 30 Autoboxing Stack Applications Generic stack implementation. Only permits reference types. Wrapper type. Each primitive type has a wrapper reference type. Ex: Integer is wrapper type for int. Wrapper type has larger set operations than primitive type. Values wrapper type are objects. Real world applications. Parsing in a compiler. Java virtual machine. Undo in a word processor. Back button in a Web browser. PostScript language for printers. Implementing function calls in a compiler. Autoboxing. Automatic cast from primitive type to wrapper type. Autounboxing. Automatic cast from wrapper type to primitive type. Stack<Integer> stack = new Stack<Integer>(); stack.(17); // Autobox (int > Integer) int a = stack.(); // Autounbox (Integer > int) 31 32

Stack Client 4: Arithmetic Expression Evaluation Arithmetic Expression Evaluation Goal. Evaluate infix expressions. operand operator Two stack algorithm. [E. W. Dijkstra] Value: onto the value stack. Operator: onto the operator stack. Left parens: ignore. Right parens: operator and two values; the result applying that operator to those values onto the operand stack. value stack operator stack public class Evaluate public static void main(string[] args) Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); String s = StdIn.readString(); if (s.equals("(")) ; else if (s.equals("+")) ops.(s); else if (s.equals("*")) ops.(s); else if (s.equals(")")) String op = ops.(); if (op.equals("+")) vals.(vals.() + vals.()); else if (op.equals("*")) vals.(vals.() * vals.()); else vals.(double.parsedouble(s)); StdOut.println(vals.()); % java Evaluate ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 101.0 33 34 Correctness Postfix Why correct? When algorithm encounters an operator surrounded by two values within parentheses, it leaves the result on the value stack. So it's as if the original input were: Repeating the argument: ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) ( 1 + ( 5 * ( 4 * 5 ) ) ) Observation 1. Remarkably, the 2stack algorithm computes the same value if the operator occurs after the two values. ( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + ) Observation 2. Now all the parentheses are redundant! 1 2 3 + 4 5 * * + ( 1 + ( 5 * 20 ) ) ( 1 + 100 ) 101 Bottom line. Postfix or "reverse Polish" notation. Jan Lukasiewicz Extensions. More ops, precedence order, associativity, whitespace. 1 + (2 3 4) * 5 * sqrt(6*6 + 7*7) 35 36

RealWorld Stack Application: PostScript Context/Definitions/Summary PostScript (WarnockGeschke, 1980s). A turtle with a stack. postfix program code add commands to drive virtual graphics machine add loops, conditionals, functions, types 20 5 1 Interpreter. Takes a program as input Does what that program would do. Simulates a virtual machine. PostScript code 100 100 moveto 100 300 lineto 300 300 lineto 300 100 lineto stroke Interpreter drawing units are points (72 per inch) PostScript code 100 100 moveto 100 300 lineto 300 300 lineto 300 100 lineto stroke define a path draw the path Simple virtual machine, but not a toy. Easy to specify published page. Easy to implement on various specific printers Revolutionized world publishing. Virtually all printed material is PostScript. 37 Compiler. Takes a program as input Produces a program as output. Produces code for a (real) machine. Java code a = 2 + 3 TOY is our proxy for a real machine Data Type and Virtual Machine are the same thing! Set values = machine state. Operations on values = machine operations. Compiler Data Structure. Represent data and relationships among data in a data type. array, linked list, compound, multiple links per node TOY code 7102 7203 1312 9330 Virtual machines you have used LFSR Stack TOY PostScript Java Virtual Machine (another stack machine) 38