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

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 17 Recursion.
Chapter 15 Lists. Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
Chapter 6 Linked Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 12: Data Structures
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 4 Linked Structures. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 4-2 Chapter Objectives Describe the use of references to create.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Stacks, Queues, and Deques
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
Chapter 12 Introduction to Collections - Stacks
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 11: Stacks and Mazes Announcements 1.Midterm.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Chapter 12 Collections. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Collections A collection is an object that helps us organize and manage.
“Planning is bringing the future into the present so that you can do something about it now.” – Alan Lakein Thought for the Day.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
1 Linked Structures, LinkedSet References as Links Linear Linked Lists and Non-linear Structures Managing Linked Lists Data Encapsulation Separate from.
Linked Structures - Review Chapter 13 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 Instructor: Scott Kristjanson.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Linked Structures, LinkedStack
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.
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
COS 312 DAY 18 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA –
Trees Chapter 19, 20 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
COS 312 DAY 23 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone progress report Overdue Assignment 6 Over Due Assignment 7 (bonus) – Due May 11 – Will.
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Next Capstone progress report is due April 25 Assignment 5 Graded – Not much original code Assignment.
Stack: a Linked Implementation
Elementary Data Structures
CHAPTER 4: Linked Structures
Chapter 12: Data Structures
Chapter 14: Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Chapter 21 Heaps and Priority Queues
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
Java Software Structures: John Lewis & Joseph Chase
Chapter 12 Recursion (methods calling themselves)
Chapter 4 Linked Structures - Stacks
Chapter 8 Recursion.
Stacks, Queues, and Deques
A type is a collection of values
Chapter 21 Heaps and Priority Queues
CHAPTER 3: Collections—Stacks
Presentation transcript:

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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 2 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 2 Scope Introduction to Linked Structures :  Object references as links  Linked vs. array-based structures  Managing linked lists  Linked implementation of a stack

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 3 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 4 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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:

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 5 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 5 Linked Non-Linear Structures Links could also be used to form more complicated, non-linear structures This is called a graph

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 6 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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; }

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 7 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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 1 2 x obj nextprev

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 8 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 9 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 10 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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 Person Node Person

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 11 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 11 Doubly 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 next previous

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 12 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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)

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 13 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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 tried- but-failed paths (2) and the successful path (3)

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 14 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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. * Java Foundations 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 15 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 15 /** * Constructor for the Maze class. Loads a maze from the given file. * Throws a FileNotFoundException if the given file is not found. * filename the name of the file to load 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 16 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 16 /** * Marks the specified position in the maze as TRIED * row the index of the row to try 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 * the number of rows in this maze */ public int getRows() { return grid.length; } /** * Return the number of columns in this maze * the number of columns in this maze */ public int getColumns() { return grid[0].length; } Traversing a Maze Implemented with Stacks

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 17 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 17 /** * Marks a given position in the maze as part of the PATH * row the index of the row to mark as part of the PATH 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. * row the row to be checked column the column to be checked 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 18 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 18 /** * Returns the maze as a string. * 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 19 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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. * Java Foundations 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 20 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 20 /** * 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 stack = new LinkedList (); 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; } Traversing a Maze Implemented with Stacks

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 21 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 21 /** * Push a new attempted move onto the stack x represents x coordinate y represents y coordinate stack the working stack of moves within the grid stack of moves within the grid */ private void push_new_pos(int x, int y, Deque 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 22 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 22 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); } Traversing a Maze Implemented with Stacks

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 23 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 23 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 class stores a generic type T and implements the same StackADT interface used previously A separate LinearNode 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 24 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 25 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 25 Implementing a Stack using Links The stack after A, B, C, and D are pushed, in that order:

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 26 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 26 Implementing a Stack using Links After E is pushed onto the stack:

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 27 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 27 package jsjf; /** * Represents a node in a linked list. * Java Foundations 4.0 */ public class LinearNode { private LinearNode next; private T element; /** * Creates an empty node. */ public LinearNode() { next = null; element = null; } /** * Creates a node storing the specified element. elem element to be stored */ public LinearNode(T elem) { next = null; element = elem; } Implementing a Stack using Links

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 28 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 28 /** * Returns the node that follows this one. reference to next node */ public LinearNode getNext() { return next; } /** * Sets the node that follows this one. node node to follow this one */ public void setNext(LinearNode node) { next = node; } /** * Returns the element stored in this node. element stored at the node */ public T getElement() { return element; } /** * Sets the element stored in this node. elem element to be stored at this node */ public void setElement(T elem) { element = elem; } Implementing a Stack using Links

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 29 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 29 package jsjf; import jsjf.exceptions.*; import java.util.Iterator; /** * Represents a linked implementation of a stack. * Java Foundations 4.0 */ public class LinkedStack implements StackADT { private int count; private LinearNode top; /** * Creates an empty stack. */ public LinkedStack() { count = 0; top = null; } Implementing a Stack using Links

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 30 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 30 /** * Adds the specified element to the top of this stack. element element to be pushed on stack */ public void push(T element) { LinearNode temp = new LinearNode (element); temp.setNext(top); top = temp; count++; } /** * Removes the element at the top of this stack and returns a * reference to it. element from top of stack 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 31 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 31 Implementing a Stack using Links

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 32 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 33 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 34 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 34 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 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

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 35 Scott Kristjanson – CMPT 125/126 – SFU Wk10.5 Slide 35 Stacks Revisited 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