COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment...

39
COS 312 DAY 19 Tony Gauvin

Transcript of COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment...

Page 1: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

COS 312 DAY 19

Tony Gauvin

Page 2: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Ch 1 -2

Agenda• Questions? • Capstone Progress reports over due • Assignment 6 Posted

– Due April 16

• Layers using non-opaque panels – Code\layered panel

• Linked Lists

Page 3: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Chapter 13

Linked Structures - Stacks

Page 4: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Chapter Scope• Object references as links• Linked vs. array-based structures• Managing linked lists• Linked implementation of a stack

13 - 4

Page 5: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Structures• An alternative to array-based implementations

are linked structures• A linked structure uses object references to

create links between objects• Recall that an object reference variable holds the

address of an object

13 - 5

Page 6: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Link”able” node

public class Person { private String name; private String address;

private Person next; // link to another person object

}

5 - 6

Page 7: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Structures• A Person object, for instance, could contain a

reference to another Person object• A series of Person objects would make up a

linked list:

13 - 7

Page 8: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Structures• Links could also be used to form more

complicated, non-linear structures

13 - 8

Page 9: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Linked Lists• There are no index values built into linked lists• To access each node in the list you must follow

the references from one node to the next

Person current = first;while (current != null){ System.out.println(current); current = current.next;}

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase 13 - 9

Page 10: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists• Care must be taken to maintain the integrity of

the links• To insert a node at the front of the list, first point

the new node to the front node, then reassign the front reference

13 - 10

http://scanftree.com/Data_Structure/Insertion-in-linked-list

Page 11: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Add node to list• Create new node• Point new node to node in front of list• Point “front” to new node

5 - 11

Page 12: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists• To delete the first node, reassign the front

reference accordingly• If the deleted node is needed elsewhere, a

reference to it must be established before reassigning the front pointer

13 - 12

http://scanftree.com/Data_Structure/Deletion-in-linked-list

Page 13: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Delete node from front of list t• Create reference (pointer) to node to be deleted• Assign front to the node the node to be deleted

pointed to

5 - 13

Page 14: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists• So far we've assumed that the list contains nodes that

are self-referential (Person points to a Person)• But often we'll want to make lists of objects that don't

contain such references• Solution: have a separate Node class that forms the list

and holds a reference to the objects being stored

13 - 14

Page 15: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked list using nodes

Public class LinkedNode< T> { private LinkedNode<T> next; private T element;

public LinkedNode(T element) { next = null; element = elem; }

public setNext(LinkedNode<T> anotherNode) { next = anotherNode; }

} 5 - 15

Page 16: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists• There are many variations on the basic linked list

concept• For example, we could create a doubly-linked list with next and previous references in each node and a separate pointer to the rear of the list

13 - 16

Page 17: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stacks Revisited• In the previous chapter we developed our own array-

based version of a stack, and we also used the java.util.Stack class from the Java API

• The API's stack class is derived from Vector, which has many non-stack abilities– http://

docs.oracle.com/javase/7/docs/api/java/util/Vector.html • It is, therefore, not the best example of inheritance,

because a stack is not a vector• It's up to the user to use a Stack object only as

intended13 - 17

Page 18: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stacks Revisited• Stack characteristics can also be found by using the Deque interface from the API

• The LinkedList class implements the Deque interface – http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html – https://

docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html • Deque stands for double-ended queue, and will be

explored further later

• For now, we will use the stack characteristics of a Deque to solve the problem of traversing a maze

13 - 18

Page 19: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Traversing a Maze• Suppose a two-dimensional maze is represented as a

grid of 1 (path) and 0 (wall) • Goal: traverse from the upper left corner to the bottom

right (no diagonal moves)

13 - 19

9 131 1 1 0 1 1 0 0 0 1 1 1 11 0 0 1 1 0 1 1 1 1 0 0 11 1 1 1 1 0 1 0 1 0 1 0 00 0 0 0 1 1 1 0 1 0 1 1 11 1 1 0 1 1 1 0 1 0 1 1 11 0 1 0 0 0 0 1 1 1 0 0 11 0 1 1 1 1 1 1 0 1 1 1 11 0 0 0 0 0 0 0 0 0 0 0 01 1 1 1 1 1 1 1 1 1 1 1 1

9 rows, 13 columns

Page 20: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stack algorithm for maze Start location (x,y) Repeat until Possible Moves Stack is empty or Maze solved (at finish location x,y) ( from current location push all possible next moves onto

Possible Moves Stack (left, right, up and down) Push current location on Made Moves Stack Peek for next move and see if you are on same path

if not pop from MM stack till you back on same path pop PM stack and move to that location

5 - 20

5 5 1 0 0 0 01 1 1 1 10 1 0 0 00 1 1 1 00 0 0 1 1

Page 21: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Traversing a Maze• Using a stack, we can perform a backtracking

algorithm to find a solution to the maze• An object representing a position in the maze is

pushed onto the stack when trying a path• If a dead end is encountered, the position is

popped and another path is tried• We'll change the integers in the maze grid to

represent tried-but-failed paths (2) and the successful path (3) – Code Example in text book is wrong

13 - 21

Page 22: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*;import java.io.*;

/** * Maze represents a maze of characters. The goal is to get from the * top left corner to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * * @author Java Foundations * @version 4.0 */public class Maze{ private static final int TRIED = 2; private static final int PATH = 3;

private int numberRows, numberColumns; private int[][] grid;

13 - 22

Page 23: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Constructor for the Maze class. Loads a maze from the given file. * Throws a FileNotFoundException if the given file is not found. * * @param filename the name of the file to load * @throws FileNotFoundException if the given file is not found */ public Maze(String filename) throws FileNotFoundException { Scanner scan = new Scanner(new File(filename)); numberRows = scan.nextInt(); numberColumns = scan.nextInt(); grid = new int[numberRows][numberColumns]; for (int i = 0; i < numberRows; i++) for (int j = 0; j < numberColumns; j++) grid[i][j] = scan.nextInt(); }

13 - 23

Page 24: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Marks the specified position in the maze as TRIED * * @param row the index of the row to try * @param col the index of the column to try */ public void tryPosition(int row, int col) { grid[row][col] = TRIED; } /** * Return the number of rows in this maze * * @return the number of rows in this maze */ public int getRows() { return grid.length; } /** * Return the number of columns in this maze * * @return the number of columns in this maze */ public int getColumns() { return grid[0].length; }

13 - 24

Page 25: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Marks a given position in the maze as part of the PATH * * @param row the index of the row to mark as part of the PATH * @param col the index of the column to mark as part of the PATH */ public void markPath(int row, int col) { grid[row][col] = PATH; }

/** * Determines if a specific location is valid. A valid location * is one that is on the grid, is not blocked, and has not been TRIED. * * @param row the row to be checked * @param column the column to be checked * @return true if the location is valid */ public boolean validPosition(int row, int column) { boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length)

// check if cell is not blocked and not previously tried if (grid[row][column] == 1) result = true;

return result; }

13 - 25

Page 26: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the maze as a string. * * @return a string representation of the maze */ public String toString() { String result = "\n";

for (int row=0; row < grid.length; row++) { for (int column=0; column < grid[row].length; column++) result += grid[row][column] + ""; result += "\n"; }

return result; }}

13 - 26

Code\chap13\Maze.java

Page 27: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*;

/** * MazeSolver attempts to traverse a Maze using a stack. The goal is to get from the * given starting position to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * * @author Java Foundations * @version 4.0 */public class MazeSolver{ private Maze maze; /** * Constructor for the MazeSolver class. */ public MazeSolver(Maze maze) { this.maze = maze; }

13 - 27

This version of the code from the textbook does not mark the correct path This hyperlinked version does mark the correct path Code\chap13\MazeSolver.java

Page 28: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Attempts to traverse the maze using a stack. Inserts special * characters indicating locations that have been TRIED and that * eventually become part of the solution PATH. * * @param row row index of current location * @param column column index of current location * @return true if the maze has been solved */ public boolean traverse() { boolean done = false; int row, column; Position pos = new Position(); Deque<Position> stack = new LinkedList<Position>(); stack.push(pos); while (!(done) && !stack.isEmpty()) { pos = stack.pop(); maze.tryPosition(pos.getx(),pos.gety()); // this cell has been tried if (pos.getx() == maze.getRows()-1 && pos.gety() == maze.getColumns()-1) done = true; // the maze is solved else { push_new_pos(pos.getx() - 1,pos.gety(), stack); push_new_pos(pos.getx() + 1,pos.gety(), stack); push_new_pos(pos.getx(),pos.gety() - 1, stack); push_new_pos(pos.getx(),pos.gety() + 1, stack); } } return done; }

13 - 28

Page 29: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Push a new attempted move onto the stack * @param x represents x coordinate * @param y represents y coordinate * @param stack the working stack of moves within the grid * @return stack of moves within the grid */ private void push_new_pos(int x, int y, Deque<Position> stack) { Position npos = new Position(); npos.setx(x); npos.sety(y); if (maze.validPosition(x,y)) stack.push(npos); }}

13 - 29

Page 30: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*;import java.io.*;

/** * MazeTester determines if a maze can be traversed. * * @author Java Foundations * @version 4.0 */public class MazeTester{ /** * Creates a new maze, prints its original form, attempts to * solve it, and prints out its final form. */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(System.in); System.out.print("Enter the name of the file containing the maze: "); String filename = scan.nextLine(); Maze labyrinth = new Maze(filename); System.out.println(labyrinth); MazeSolver solver = new MazeSolver(labyrinth);

if (solver.traverse()) System.out.println("The maze was successfully traversed!"); else System.out.println("There is no possible path.");

System.out.println(labyrinth); }} Code\chap13\MazeTester.java

13 - 30

Page 31: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links• Let's now implement our own version of a stack

that uses a linked list to hold the elements• Our LinkedStack<T> class stores a generic

type T and implements the same StackADT<T> interface used previously

• A separate LinearNode<T> class forms the list and hold a reference to the element stored

• An integer count will store how many elements are currently in the stack

13 - 31

Page 32: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links• Since all activity on a stack happens on one end,

a single reference to the front of the list will represent the top of the stack

13 - 32

Page 33: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links• The stack after A, B, C, and D are pushed, in that

order:

13 - 33

Page 34: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links• After E is pushed onto the stack:

13 - 34

Page 35: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf;

/** * Represents a node in a linked list. * * @author Java Foundations * @version 4.0 */public class LinearNode<T>{ private LinearNode<T> next; private T element; /** * Creates an empty node. */ public LinearNode() { next = null; element = null; } /** * Creates a node storing the specified element. * @param elem element to be stored */ public LinearNode(T elem) { next = null; element = elem; }

13 - 35

Page 36: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the node that follows this one. * @return reference to next node */ public LinearNode<T> getNext() { return next; } /** * Sets the node that follows this one. * @param node node to follow this one */ public void setNext(LinearNode<T> node) { next = node; } /** * Returns the element stored in this node. * @return element stored at the node */ public T getElement() { return element; } /** * Sets the element stored in this node. * @param elem element to be stored at this node */ public void setElement(T elem) { element = elem; }} Code\chap13\jsjf\LinearNode.java

13 - 36

Page 37: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf;

import jsjf.exceptions.*;import java.util.Iterator;

/** * Represents a linked implementation of a stack. * * @author Java Foundations * @version 4.0 */public class LinkedStack<T> implements StackADT<T>{ private int count; private LinearNode<T> top;

/** * Creates an empty stack. */ public LinkedStack() { count = 0; top = null; }

13 - 37

Page 38: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified element to the top of this stack. * @param element element to be pushed on stack */ public void push(T element) { LinearNode<T> temp = new LinearNode<T>(element);

temp.setNext(top); top = temp; count++; }

/** * Removes the element at the top of this stack and returns a * reference to it. * @return element from top of stack * @throws EmptyCollectionException if the stack is empty */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack");

T result = top.getElement(); top = top.getNext(); count--; return result; } Code\chap13\jsjf\LinkedStack.java

13 - 38

Page 39: COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.

Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links

13 - 39