The Singleton Pattern II Recursive Linked Structures.

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

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Chapter 7. Binary Search Trees
CO /1075 Recursion on linked lists All the linked list examples we have seen so far use iteration when they need to work through the nodes of a.
Data Structures ADT List
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
John Hurley Cal State LA
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
Java Review Interface, Casting, Generics, Iterator.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Object Oriented Programming in Java. Object Oriented Programming Concepts in Java Object oriented Programming is a paradigm or organizing principle for.
Variations on Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: A Pseudocode Approach with C 1 Chapter 5 Contd... Objectives Explain the design, use, and operation of a linear list Implement a linear.
Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
COMP103 - Linked Lists (Part A)1 Chapter 17 Truly dynamic memory management.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
COSC 2006 Data Structures I Recursion II
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
“Planning is bringing the future into the present so that you can do something about it now.” – Alan Lakein Thought for the Day.
CSC 211 Data Structures Lecture 13
CHAPTER 4 RECURSION. BASICALLY, A METHOD IS RECURSIVE IF IT INCLUDES A CALL TO ITSELF.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Week 5 - Wednesday.  What did we talk about last time?  Recursion  Definitions: base case, recursive case  Recursive methods in Java.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
LINKED LIST’S EXAMPLES Salim Malakouti. Linked List? 523 Pointer Node ValuePointer.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
TOWERS OF HANOI. : If n = 1, move disk 1 from pole 'A' to pole 'B'. else: 1.First, move n-1 disks from pole 'A' to pole 'C', using pole 'B' as.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
CSE 143 Lecture 9: introduction to recursion reading: 12.1.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Linked Data Structures
Lecture 9: introduction to recursion reading: 12.1
Recursion what is it? how to build recursive algorithms
Building Java Programs
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Binary Search one reason that we care about sorting is that it is much faster to search a sorted list compared to sorting an unsorted list the classic.
Trees.
Binary Trees.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Graphs and Cycles.
null, true, and false are also reserved.
Data Structures ADT List
Data Structures ADT List
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Data Structures ADT List
Recursive Objects Singly Linked Lists.
ITI Introduction to Computing II Lab-12
Building Java Programs
Presentation transcript:

The Singleton Pattern II Recursive Linked Structures

Recursive Data Structures A recursive data structure is either a basic value, such as null, or contains a value of the same type of data structure The OneWayNode class is a good example

public class OneWayNode{ public String value; public OneWayNode next; public OneWayNode(String s, OneWayNode n){ value = s; next = n; } The OneWayNode Class OneWayNode head = new OneWayNode("A", new OneWayNode("B", null)); “A”“A”“B”“B” head

Recursive Data Structures A linked structure is either –empty ( null ) or –contains a data value followed by another linked structure ( next ) of exactly the same form

Recursive Algorithms When processing a linked structure –Handle the case of empty ( null ) –Do something with the data value and then “ recurse ” with the linked structure ( next ) of exactly the same form –Package the algorithms as static methods in a toolbox class (like Math )

if the linked structure is not empty process the value process the rest of the linked structure Some Recursive Patterns: Traversals Note that there is an if statement rather than a while loop The process just quits when the base case (the end of the structure) is reached

static void traverse(OneWayNode n){ if (n != null){ process(n.value) traverse(n.next); } Some Recursive Patterns: Traversals “A”“A”“B”“B” head n

static void traverse(OneWayNode n){ if (n != null){ process(n.value) traverse(n.next); } Some Recursive Patterns: Traversals “A”“A”“B”“B” head n n

static void traverse(OneWayNode n){ if (n != null){ process(n.value) traverse(n.next); } Some Recursive Patterns: Traversals “A”“A”“B”“B” head n n n

if the linked structure is empty return false else if the target equals the value return true else return the result of searching the rest of the linked structure Some Recursive Patterns: Search

static boolean contains(OneWayNode n, String target){ if (n == null) return false; else if (target.equals(n.value)) return true; else return contains(n.next, target); } Some Recursive Patterns: Search “A”“A”“B”“B” head

check preconditions if i == 0 return the value else return the result of getting from the rest of the linked structure at i - 1 Some Recursive Patterns: get(i)

static String get(OneWayNode n, int i){ if (i = length(n) throw new IllegalArgumentException( "Index out of range"); if (i == 0) return n.value; else return get(n.next, i - 1); } Some Recursive Patterns: get(i) “A”“A”“B”“B” head

if the linked structure is empty return 0 else return 1 + the length of the rest of the linked structure Some Recursive Patterns: length

static int length(OneWayNode n){ if (n == null) return 0; else return 1 + length(n.next); } Some Recursive Patterns: length “A”“A”“B”“B” head

if the linked structure is empty return null else return a new node whose value is the value and whose next is the result of copying the rest of the linked structure Some Recursive Patterns: Copy the Structure

static OneWayNode copy(OneWayNode n){ if (n == null) return null; else return new OneWayNode(n.value, copy(n.next)); } Some Recursive Patterns: Copy the Structure “A”“A”“B”“B” head

Recursion and Data Structures Recursive algorithms can be used to “ back up ” through a data structure, such as a string or a linked structure The calls move forward, and the real work is done after each call returns or “ backs up ”

if the linked structure is not empty process the rest of the linked structure process the value Some Recursive Patterns: Right to Left Traversals Note we just invert the order of the two statements within the if statement As the recursion unwinds from the end, each value is processed

Some Recursive Patterns: Right to Left Traversals “A”“A”“B”“B” head static void backtrack(OneWayNode n){ if (n != null){ backtrack(n.next); process(n.value); } n

Some Recursive Patterns: Right to Left Traversals “A”“A”“B”“B” head static void backtrack(OneWayNode n){ if (n != null){ backtrack(n.next); process(n.value); } n n

Some Recursive Patterns: Right to Left Traversals “A”“A”“B”“B” head static void backtrack(OneWayNode n){ if (n != null){ backtrack(n.next); process(n.value); } n n n

Some Recursive Patterns: Right to Left Traversals “A”“A”“B”“B” head static void backtrack(OneWayNode n){ if (n != null){ backtrack(n.next); process(n.value); } n n

Some Recursive Patterns: Right to Left Traversals “A”“A”“B”“B” head static void backtrack(OneWayNode n){ if (n != null){ backtrack(n.next); process(n.value); } n

static void reverseOutput(OneWayNode n){ if (n != null){ reverseOutput(n.next); System.out.println(n.value); } Some Recursive Patterns: Output in Reverse “A”“A”“B”“B” head

Problems With Current Version Uses static methods for all of the processing, not very object-oriented Uses null for the case of an empty structure, so we must check for null with if statements in every method OneWayNode n = new OneWayNode("Ken", null); int myLength = NodeMethods.length(n);

Problems With Current Version A linked structure should be able to compute its own length But a recursive implementation of this would be pretty hard OneWayNode n = new OneWayNode("Ken", null); int myLength = n.length();

Our View of the Current Version A linked structure is either –empty ( null ) or –contains a data value followed by another linked structure ( next ) of exactly the same form

A Better View A linked structure is either –empty (an empty node) or –compound (a compound node that contains a data value and another linked structure)

From Data to Algorithms Two concrete classes of nodes that implement the same interface The empty node ’ s methods handle the base cases The compound node ’ s methods handle the recursive ones Use polymorphism to make the choices (no explicit if statements in the code!)

From Data to Algorithms OneWayNode CompoundNodeEmptyNode

public interface OneWayNode{ public void traverse(Visitor v); public void backwardTraverse(Visitor v); public int length(); public OneWayNode copy(); public OneWayNode reverse(); public OneWayNode reverse(OneWayNode result); } The OneWayNode Interface A Visitor is an object that runs a method visit to process each value during a traversal

public interface Visitor{ public void visit(String s); } Creating and Using a Visitor A Visitor is an object that runs a method visit to process each value during a traversal Visitor v = new Visitor(){ public void visit(String s){ System.out.print(s + " "); } }; aOneWayNode.traverse(v); aOneWayNode.backwardTraverse(v);

Node Classes, Etc. EmptyNode – The class of an empty node CompoundNode – The class of compound nodes EmptyNode.THE_EMPTY_NODE – The single instance used for any empty node

public class NodeTester{ public static void main (String[] args){ String[] strings = {"Bill", "Mary", "Sam", "Sue"}; OneWayNode n1 = EmptyNode.THE_EMPTY_NODE; for (int i = 0; i < strings.length; i++) n1 = new CompoundNode(strings[i], n1); Visitor v = new Visitor(){ public void visit(String s){ System.out.print(s + " "); } }; System.out.println(n1.length()); System.out.print("["); n1.traverse(v); System.out.println("]"); System.out.print("["); n1.backwardTraverse(v); System.out.println("]"); OneWayNode n2 = n1.copy(); OneWayNode n3 = n1.reverse(); } Using the New Structure

public interface OneWayNode{ public void traverse(Visitor v); public void backwardTraverse(Visitor v); public int length(); public OneWayNode copy(); public OneWayNode reverse(); public OneWayNode reverse(OneWayNode result); } The OneWayNode Interface

public class EmptyNode implements OneWayNode{ public void traverse(Visitor v){return;} public void backwardTraverse(Visitor v){return;} public int length(){return 0;} public OneWayNode copy(){return THE_EMPTY_NODE;} public OneWayNode reverse(){ return THE_EMPTY_NODE; } public OneWayNode reverse(OneWayNode result){ return THE_EMPTY_NODE; } static public final OneWayNode THE_EMPTY_NODE = new EmptyNode(); } The EmptyNode Class The singleton instance is created just once

public class CompoundNode implements OneWayNode{ private String value; private OneWayNode next; public CompoundNode(String value, OneWayNode next){ this.value = value; this.next = next; } public CompoundNode(){ this("", EmptyNode.THE_EMPTY_NODE); } public void traverse(Visitor v){ // NO IF STATEMENTS! v.visit(value); next.traverse(v); } public void backwardTraverse(Visitor v){ next.backwardTraverse(v); v.visit(value); } The CompoundNode Class

public int length(){ return 1 + next.length(); } public OneWayNode copy(){ return new CompoundNode(value, next.copy()); } public OneWayNode reverse(){ return reverse(EmptyNode.THE_EMPTY_NODE); } public OneWayNode reverse(OneWayNode result){ return next.reverse(new CompoundNode(value, result)); } The CompoundNode Class

Recursive Objects Instead of using explicit if statements to handle choices, try using polymorphism, which automatically handles them Divide the cases into different types of objects that obey the same interface (avoid using null for the simple case) Use simple objects for the base cases and recursive objects for the recursive ones