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

Similar documents
Linked Structures - Review Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Graphs Chapter 24. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Analysis of Algorithms Chapter 11. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Announcements Queues. Queues

Searching and Sorting Chapter 18. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Bonus Puzzle #1 Random Doubles [0,5] Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Arrays Chapter 7. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

A queue is a linear collection whose elements are added on one end and removed from the other

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

CSCD 326 Data Structures I Stacks

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CS350: Data Structures Stacks

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

Introduction to Computer Science II (CSI 1101) Final Examination

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Queue rear tail front head FIFO

Why use recursion? Some problems are more easily expressed in a recursive definition

CE204 Data Structures and Algorithms Part 2

STUDENT LESSON AB24 Recursive Array Programming

Linked Lists. References and objects

csci 210: Data Structures Stacks and Queues

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

CMPSCI 187: Programming With Data Structures. Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

Lists. ordered lists unordered lists indexed lists 9-3

(3-2) Basics of a Stack. Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University

Solutions to a few of the review problems:

Dynamic Data Structures

COM S 211/ENGRD 211 May 15, 2003

Stacks and Queues. David Greenstein Monta Vista

Supplement: Case Study: Sudoku. For Introduction to Java Programming By Y. Daniel Liang

Introduction to Computer Science II (ITI 1121) Final Examination

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Stacks and Queues as Collections

CSE 143. Lecture 7: Linked List Basics reading: 16.2

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

CS 307 Final Fall 2009

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

Stacks and Their Applications

Data Structure: Lists and Iterators. Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

ECE Fall st Midterm Examination (120 Minutes, closed book)

Basic Data Structures

Implementing Dynamic Data Structures

Basic Data Structures 1 / 24

LECTURE OBJECTIVES 6-2

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

Linked Lists. Chapter 12.3 in Savitch

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Stacks Fall 2018 Margaret Reid-Miller

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Topic 6: Inner Classes

Introduction to Linked Data Structures

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

EEL 3801 Introduction to Computer Engineering Summer Home Work Schedule

Introduction to Computer Science II (ITI 1121) Midterm Examination

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Building Java Programs

Class 26: Linked Lists

Array. Prepared By - Rifat Shahriyar

H212 Introduction to Software Systems Honors

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) Midterm Examination

Building Java Programs

Introduction to Computing II (ITI 1121) Final Examination

Linked List. ape hen dog cat fox. tail. head. count 5

CSE 143 SAMPLE MIDTERM

Chapter 13: Collections Lab Exercises

CMSC 341 Lecture 7 Lists

Unit 4: Stacks and Queues

Building Java Programs

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015

CS61B Spring 2016 Guerrilla Section 2 Worksheet

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

MIDTERM REVIEW. midterminformation.htm

Recitation: Loop Jul 7, 2008

CMPS 240 Data Structures and Algorithms Test #2 Fall 2017 November 15

Transcription:

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

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

3 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 Wk10.5 Slide 3

4 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: Wk10.5 Slide 4

5 Linked Non-Linear Structures Links could also be used to form more complicated, non-linear structures This is called a graph Wk10.5 Slide 5

6 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 = firstperson; while (current!= null) System.out.println(current); current = current.next; Wk10.5 Slide 6

7 Linked Lists Inserting a node in the Middle 1. Set the next member in obj to refer to the next object in the list 2. Set the next member of the previous object to refer to the new object obj 1 2 prev x next Wk10.5 Slide 7

8 Linked Lists Inserting a node at the front 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 Wk10.5 Slide 8

9 Linked Lists Deleting the First Node 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 Wk10.5 Slide 9

10 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 references Solution: have a separate Node class that forms the list and holds a reference to the objects being stored Node Node Node Node Node Node Person Person Person Person Person Person Wk10.5 Slide 10

Doubly Linked Lists 11 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 next previous Wk10.5 Slide 11

12 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 13 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 0 1 1 0 1 1 1 1 0 0 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 Wk10.5 Slide 12

13 Using Stacks for 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 triedbut-failed paths (2) and the successful path (3) Wk10.5 Slide 13

Traversing a Maze Implemented with Stacks 14 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; Wk10.5 Slide 14

Traversing a Maze Implemented with Stacks 15 * 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(); Wk10.5 Slide 15

16 Traversing a Maze Implemented with Stacks * 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; Wk10.5 Slide 16

Traversing a Maze Implemented with Stacks 17 * 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; Wk10.5 Slide 17

Traversing a Maze Implemented with Stacks 18 * 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; Wk10.5 Slide 18

Traversing a Maze Implemented with Stacks 19 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; Wk10.5 Slide 19

20 Traversing a Maze Implemented with Stacks * 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 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; Wk10.5 Slide 20

Traversing a Maze Implemented with Stacks 21 * 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); Wk10.5 Slide 21

22 Traversing a Maze Implemented with Stacks 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); Wk10.5 Slide 22

Implementing a Stack using Links 23 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 Wk10.5 Slide 23

24 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 Wk10.5 Slide 24

25 Implementing a Stack using Links The stack after A, B, C, and D are pushed, in that order: Wk10.5 Slide 25

26 Implementing a Stack using Links After E is pushed onto the stack: Wk10.5 Slide 26

Implementing a Stack using Links 27 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; Wk10.5 Slide 27

28 Implementing a Stack using Links * 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; Wk10.5 Slide 28

29 Implementing a Stack using Links 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; Wk10.5 Slide 29

30 Implementing a Stack using Links * 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; Wk10.5 Slide 30

31 Implementing a Stack using Links Wk10.5 Slide 31

32 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 Wk10.5 Slide 32

33 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 Wk10.5 Slide 33

Stacks Revisited 34 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 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 intended Wk10.5 Slide 34

Stacks Revisited 35 Stack characteristics can also be found by using the Deque interface from the API The LinkedList class implements the Deque interface 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 Wk10.5 Slide 35