Top Banner
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
35

wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Jun 26, 2018

Download

Documents

lamdang
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Linked Structures Chapter 13

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Page 2: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 2Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

2

Scott Kristjanson – CMPT 125/126 – SFU

Scope

Introduction to Linked Structures: Object references as links Linked vs. array-based structures Managing linked lists Linked implementation of a stack

Page 3: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 3Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

3

Scott Kristjanson – CMPT 125/126 – SFU

Linked Structures

An alternative to array-based implementations are linked structuresA linked structure uses object references to create links between objectsRecall that an object reference variable holds the address of an object

Page 4: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 4Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

4

Scott Kristjanson – CMPT 125/126 – SFU

Linked Lists

A Person object could contain a reference to another Person

public class Person{private String name;private String addr;private Person next; // Link to Another Person object

}

A series of Person objects could make up a linked list:

Page 5: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 5Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

5

Scott Kristjanson – CMPT 125/126 – SFU

Linked Non-Linear Structures

Links could also be used to form more complicated, non-linear structures

This is called a graph

Page 6: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 6Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

6

Scott Kristjanson – CMPT 125/126 – SFU

Linked Lists

There are no index values built into linked listsTo access each node in the list you must follow the references from one node to the next

Person current = firstPerson;

while (current != null)

{

System.out.println(current);

current = current.next;

}

Page 7: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 7Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

7

Scott Kristjanson – CMPT 125/126 – SFU

Linked Lists – Inserting a node in the Middle

1. Set the “next” member in obj to refer to the next object in the list2. Set the “next” member of the previous object to refer to the new object

1

2

x

obj

nextprev

Page 8: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 8Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

8

Scott Kristjanson – CMPT 125/126 – SFU

Linked Lists – Inserting a node at the front

Care must be taken to maintain the integrity of the linksTo insert a node at the front of the list, first point the new node to the front node, then reassign the front reference

Page 9: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 9Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

9

Scott Kristjanson – CMPT 125/126 – SFU

Linked Lists – Deleting the First Node

To delete the first node, reassign the front reference accordinglyIf the deleted node is needed elsewhere, a reference to it must be established before reassigning the front pointer

Page 10: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 10Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

10

Scott Kristjanson – CMPT 125/126 – SFU

Put Linked List Details into separate Node Class

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 referencesSolution: have a separate Node class that forms the list and holds a reference to the objects being stored

Node

Person

Node Node Node Node Node

Person Person Person Person Person

Page 11: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 11Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

11

Scott Kristjanson – CMPT 125/126 – SFU

Doubly Linked Lists

There are many variations on the basic linked list conceptFor 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

next

previous

Page 12: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 12Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

12

Scott Kristjanson – CMPT 125/126 – SFU

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)

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

Page 13: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 13Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

13

Scott Kristjanson – CMPT 125/126 – SFU

Using Stacks for Traversing a Maze

Using a stack, we can perform a backtracking algorithm to find a solution to the mazeAn object representing a position in the maze is pushed onto the stack when trying a pathIf a dead end is encountered, the position is popped and another path is triedWe'll change the integers in the maze grid to represent tried-but-failed paths (2) and the successful path (3)

Page 14: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 14Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

14

Scott Kristjanson – CMPT 125/126 – SFU

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;

Traversing a Maze Implemented with Stacks

Page 15: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 15Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

15

Scott Kristjanson – CMPT 125/126 – SFU

/**

* 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();

}

Traversing a Maze Implemented with Stacks

Page 16: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 16Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

16

Scott Kristjanson – CMPT 125/126 – SFU

/*** 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;}

Traversing a Maze Implemented with Stacks

Page 17: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 17Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

17

Scott Kristjanson – CMPT 125/126 – SFU

/**

* 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;

}

Traversing a Maze Implemented with Stacks

Page 18: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 18Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

18

Scott Kristjanson – CMPT 125/126 – SFU

/**

* 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;

}

}

Traversing a Maze Implemented with Stacks

Page 19: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 19Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

19

Scott Kristjanson – CMPT 125/126 – SFU

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;

}

Traversing a Maze Implemented with Stacks

Page 20: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 20Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

20

Scott Kristjanson – CMPT 125/126 – SFU

/*** 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.*/

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 triedif (pos.getx() == maze.getRows()-1 && pos.gety() == maze.getColumns()-1)

done = true; // the maze is solvedelse{

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;

}

Traversing a Maze Implemented with Stacks

Page 21: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 21Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

21

Scott Kristjanson – CMPT 125/126 – SFU

/**

* 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);

}

}

Traversing a Maze Implemented with Stacks

Page 22: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 22Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

22

Scott Kristjanson – CMPT 125/126 – SFU

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!");

elseSystem.out.println("There is no possible path.");

System.out.println(labyrinth);}

}

Traversing a Maze Implemented with Stacks

Page 23: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 23Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

23

Scott Kristjanson – CMPT 125/126 – SFU

Implementing a Stack using Links

Let's now implement our own version of a stack that uses a linked list to hold the elementsOur LinkedStack<T> class stores a generic type T and implements the same StackADT<T> interface used previouslyA separate LinearNode<T> class forms the list and hold a reference to the element storedAn integer count will store how many elements are currently in the stack

Page 24: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 24Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

24

Scott Kristjanson – CMPT 125/126 – SFU

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 thestack

Page 25: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 25Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

25

Scott Kristjanson – CMPT 125/126 – SFU

Implementing a Stack using Links

The stack after A, B, C, and D are pushed, in that order:

Page 26: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 26Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

26

Scott Kristjanson – CMPT 125/126 – SFU

Implementing a Stack using Links

After E is pushed onto the stack:

Page 27: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 27Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

27

Scott Kristjanson – CMPT 125/126 – SFU

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;

}

Implementing a Stack using Links

Page 28: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 28Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

28

Scott Kristjanson – CMPT 125/126 – SFU

/*** 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;}

}

Implementing a Stack using Links

Page 29: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 29Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

29

Scott Kristjanson – CMPT 125/126 – SFU

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;

}

Implementing a Stack using Links

Page 30: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 30Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

30

Scott Kristjanson – CMPT 125/126 – SFU

/*** 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;}

Implementing a Stack using Links

Page 31: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 31Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

31

Scott Kristjanson – CMPT 125/126 – SFU

Implementing a Stack using Links

Page 32: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 32Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

32

Scott Kristjanson – CMPT 125/126 – SFU

Key Things to take away:

Linked Objects:• Object Reference variables can be used to create linked structures• A Linked List is composed on objects that each point to the next in the list• Objects stored in a collection should not contain any implementation

details of the underlying data structure that • The order in which references are changed are very important• Dealing with the first node in the list often requires special handling• A Linked List implementation of a Stack adds elements to, or removes

elements from, one end of the linked list.• Queues, Trees, and other structures can be created with Linked Objects

Page 33: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 33Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

33

Scott Kristjanson – CMPT 125/126 – SFU

References:

1. J. Lewis, P. DePasquale, and J. Chase., Java Foundations: Introduction to Program Design & Data Structures. Addison-Wesley, Boston, Massachusetts, 3rd edition, 2014, ISBN 978-0-13-337046-1

Page 34: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 34Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

34

Scott Kristjanson – CMPT 125/126 – SFU

Stacks Revisited

In the previous chapter we developed our own array-based version of a stack, and we also used the java.util.Stackclass from the Java APIThe API's stack class is derived from Vector, which has many non-stack abilitiesIt is, therefore, not the best example of inheritance, because astack is not a vectorIt's up to the user to use a Stack object only as intended

Page 35: wk10.5 - Linked Structures - Simon Fraser University · Linked Structures Chapter 13 ... Linked Lists There are no index values built into linked lists To access each node in the

Wk10.5 Slide 35Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

35

Scott Kristjanson – CMPT 125/126 – SFU

Stacks Revisited

Stack characteristics can also be found by using the Dequeinterface from the APIThe LinkedList class implements the Deque interfaceDeque stands for double-ended queue, and will be explored further laterFor now, we will use the stack characteristics of a Deque to solve the problem of traversing a maze