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

Similar documents
Linked Structures 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

Graphs Chapter 24. 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

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

Announcements Queues. Queues

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

Introduction to Computing II (ITI 1121) Final Examination

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

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

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

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

Queue rear tail front head FIFO

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

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

LECTURE OBJECTIVES 6-2

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

Introduction to Computer Science II (ITI 1121) Midterm Examination

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

Introduction to Computer Science II (ITI 1121) Final Examination

Lists. ordered lists unordered lists indexed lists 9-3

CSE 143 SAMPLE MIDTERM

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

Midterm Solutions. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

CS350: Data Structures Stacks

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

ADTs, Arrays, Linked Lists

Introduction to Computer Science II (CSI 1101) Final Examination

CSIS 10B Lab 2 Bags and Stacks

CE204 Data Structures and Algorithms Part 2

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

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

CS 101 Spring 2006 Final Exam Name: ID:

CMSC 132: Object-Oriented Programming II. Stack and Queue

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

CSCD 326 Data Structures I Stacks

CS132 Algorithm. Instructor: Jialiang Lu Office: Information Center 703

Stacks Fall 2018 Margaret Reid-Miller

CS 307 Final Fall 2009

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Basic Data Structures

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

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

Has-a Relationships. A pen has a or contains a ball

Basic Data Structures 1 / 24

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COE 312 Data Structures. Welcome to Exam II Monday November 23, Instructor: Dr. Wissam F. Fawaz

Generics in Java. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Motivating Example: Observations (1) Generics in Java. Motivating Example: A Book of Objects. Motivating Example: Observations (2)

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt

Stacks and Queues. Chapter Stacks

Sample file. Practice Exam One COMPUTER SCIENCE A SECTION I. Directions: Determine the answer to each of the following questions or incomplete

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Introduction to Linked Data Structures

Debugging [continued]

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

CS 112 Introduction to Programming

Class 26: Linked Lists

1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write

COP 3330 Final Exam Review

1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.

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

CSE 143 SAMPLE MIDTERM SOLUTION

Computer Science CS221 Test 2 Name. 1. Give a definition of the following terms, and include a brief example. a) Big Oh

1/27/2014. OO design approach with examples. UML and project clarifications (2) Project clarifications 1. UML

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

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

Inf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin

Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008

Question 1 [20 points]

Linked Lists. References and objects

Lecture 3 Linear Data Structures

Solution for Data Structure

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

CS 126 Midterm Review Session

Inf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.)

CS61B Spring 2016 Guerrilla Section 2 Worksheet

Linked Lists. Chapter 12.3 in Savitch

University of Palestine. Mid Exam Total Grade: 100

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Refresher: Interface Specifications. ADT Documentation. Set Represented as an Array. Representation Invariant, Abstraction Function

Queues Fall 2018 Margaret Reid-Miller

Representation Invariant, Abstraction Function

Debugging [continued]

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

Lecture 3 Linear Data Structures

Stacks and Their Applications

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

CS 61B Spring 2017 Guerrilla Section 3 Worksheet. 25 February 2017

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

csci 210: Data Structures Stacks and Queues

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Odds and Ends. (!) Wed night dinner, Monroe 5:30 Acknowledge assistance as appropriate

Chapter 8 STRUCTURES IN C

Transcription:

Linked Structures - Review 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 Wk14.1 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 Wk14.1 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: Wk14.1 Slide 4

5 Linked Non-Linear Structures Links could also be used to form more complicated, non-linear structures This is called a graph Wk14.1 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; Wk14.1 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 Wk14.1 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 Wk14.1 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 Wk14.1 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 Wk14.1 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 Node Node Node Node Node Node previous Person Person Person Person Person Person Wk14.1 Slide 11

12 Implementing a Stack using Links Let's implement a stack using 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 Wk14.1 Slide 12

13 LinkedStack<T> public class LinkedStack<T> implements StackADT<T> { private int count; private LinearNode<T> top; /** * Creates an empty stack. LinkedStack<T> */ public LinkedStack() { count = 0; top = null; LinearNode<T> top int count Linear Node<T> Wk14.1 Slide 13

14 LinearNode<T> public class LinearNode<T> { private LinearNode<T> next; private T element; LinearNode<t> top public LinearNode() { next = null; element = null; public LinearNode(T elem) { next = null; element = elem; public LinearNode<T> getnext() { return next; LinearNode<t> next T element Object of Class T Linear Node<T> public void setnext(linearnode<t> node) { next = node; public T getelement() { return element; public void setelement(t elem) { element = elem; Wk14.1 Slide 14

15 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 Linear Node Linear Node Linear Node Linear Node Linear Node Linear Node T T T T T T Wk14.1 Slide 15

16 Implementing a Stack using Links The stack after A, B, C, and D are pushed, in that order: Wk14.1 Slide 16

17 Implementing a Stack using Links After E is pushed onto the stack: Wk14.1 Slide 17

Implementing a Stack using Links 18 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; Wk14.1 Slide 18

19 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; Wk14.1 Slide 19

20 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; Wk14.1 Slide 20

21 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; Wk14.1 Slide 21

22 Implementing a Stack using Links Wk14.1 Slide 22

23 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 Wk14.1 Slide 23

24 Practice Array Questions Problem 1: Write a program that shuffles a deck of cards, then deals out 5 cards each to two players. Problem 2: Create a method that accepts two 2-dimensional arrays A and B as formal parameters and returns the matrix product A*B. Problem 3: What is wrong with Bob s Array code? Problem 4: Write a method called sumarray that accepts an array of floating point values and returns the sum of the values stored in the array Problem 5: Write a method called sum2darray that accepts an int[][] array and sums all the numbers in the array and returns the sum of the values stored in the array. Wk14.1 Slide 24

25 Problem 1: Write a program to shuffle and deal cards Step 1: Create the Shuffled Deck using a Stack for(int i=0; i<card.numsuits*card.numvalues; i++) { boolean foundnextcard = false; int tries = 0; while (!foundnextcard) { int cardvalue = valuegen.nextint(card.numvalues); int cardsuit = suitgen.nextint(card.numsuits ); tries++; if (carddealt[cardsuit][cardvalue] == false) { Card nextcard = new Card(cardValue+1, cardsuit); deckofcards.push(nextcard); carddealt[cardsuit][cardvalue] = true; foundnextcard = true; System.out.println("Card "+(i+1)+" : "+ nextcard+" found after "+tries+" tries"); Wk14.1 Slide 25

26 Problem 1: Write a program to shuffle and deal cards Step 2: Deal five cards to each player for(int p=0; p<numplayers; p++) for(int c=0; c<numcardsperhand; c++) hand[p][c] = deckofcards.pop(); Wk14.1 Slide 26

27 Problem 1: Write a program to shuffle and deal cards Step 3: Display both player s hands for(int p=0; p<numplayers; p++) { System.out.println("\nPlayer "+p+" hand:"); for(int c=0; c<numcardsperhand; c++) { System.out.println( "Card " + c + ": "+hand[p][c]); Wk14.1 Slide 27

28 Problem 1: Write a program to shuffle and deal cards Discussion: How does a Card get converted to a String? System.out.println("Card "+c+": "+hand[p][c]); Using the tostring method from the Card class! public String tostring() { if (value == 0) return "Joker"; else return cardnames[value]+" of "+suit; enum Suit {Hearts, Diamonds, Clubs, Spades; private final static String[] cardnames = {"Joker","Ace", "Two", "Three","Four","Five", "Six", "Seven","Eight","Nine","Ten", "Jack","Queen","King"; Wk14.1 Slide 28

29 Problem 2: Method to return the matrix product A*B. public static int[][] matrixmultiply(int[][] A, int [][] B) { int arows = A.length; int acols = A[0].length; int brows = B.length; int bcols = B[0].length; int N = A.length; // Assume A and B are both NxN if (acols!= brows) throw new IllegalArgumentException( "A Columns: " + acols + " did not match number of B Rows " + brows); int[][] C = new int[arows][bcols]; for (int i = 0; i < arows; i++) // A Row for (int j = 0; j < bcols; j++) // B Column for (int k = 0; k < acols; k++) // A Column C[i][j] += A[i][k] * B[k][j]; return C; Wk14.1 Slide 29

30 And the Winner for best TicTacToe GUI is Curtis Babnik Human vs Smarter: http://www.youtube.com/watch?v=nzyvr0v3ixs Human vs Learns : http://www.youtube.com/watch?v=t87ufmkbege Wk14.1 Slide 30

31 TicTacToe UML A UML Diagram using a Eclipse UML Plugin: Wk14.1 Slide 31

32 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 Wk14.1 Slide 32