Linked Bag Chapter 3.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
CHAPTER 7 Queues.
A Bag Implementation that Links Data Chapter 3 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Lists Lists as an abstract data type (ADT)
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Bag Implementations that Use Arrays Chapter 2 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 3: Arrays, Linked Lists, and Recursion
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
Chapter 7 More Lists. Chapter 7: More Lists 7.1 – Circular Linked Lists 7.2 – Doubly Linked Lists 7.3 – Linked Lists with Headers and Trailers 7.4 – A.
Bags Chapter 1 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
ArrayList, Multidimensional Arrays
Abstract Data Types Chapter 1. Today n Data Types & Abstract Data Types n Designing Systems and ADTs use casesuse cases class-responsibility-collaboration.
Simulated Pointers Limitations Of Java Pointers May be used for internal data structures only. Data structure backup requires serialization and deserialization.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
LINKED LISTS Linear Linked List. November 1, 2005Linked Lists2 of 48 Linked Lists Like stacks and queues, linked lists are lists of nodes that point to.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
QUEUES What are Queues? Creating a Queue Enqueuing and Dequeuing Testing for an Empty Queue.
1 Linked Structures, LinkedSet References as Links Linear Linked Lists and Non-linear Structures Managing Linked Lists Data Encapsulation Separate from.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Bag Implementations that Use Arrays Chapter 2 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions.
Winter 2006CISC121 - Prof. McLeod1 Stuff Deadline for assn 3 extended to Monday, the 13 th. Please note that the testing class for assn 3 has changed.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
2015-T2 Lecture 17 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, John Lewis,
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Linked Lists Chapter 4. Linked Structures: Motivations Arrays have fixed size –Problematic for data structures of arbitrary size Arrays order items physically.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Chapter 7 Queues Introduction Queue applications Implementations.
1. What is it? It is a queue that access elements according to their importance value. Eg. A person with broken back should be treated before a person.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
Array-Based Implementations Chapter 3 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
A Bag Implementation that Links Data Chapter 3 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions.
Data Structures Arrays and Lists Part 2 More List Operations.
Question of the Day  What three letter word completes the first word and starts the second one: DON???CAR.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
Link-Based Implementations
Lists CS 3358.
Bag Implementations that Use Arrays
A Bag Implementation that Links Data
Prof. Neary Adapted from slides by Dr. Katherine Gibson
A Bag Implementation that Links Data
Linked Lists.
Chapter 4 Link Based Implementations
Arrays versus ArrayList
Adapted from Pearson Education, Inc.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
A List Implementation That Links Data
Lists.
CSC 143 Java Linked Lists.
Lecture 6: Linked Data Structures
Programming II (CS300) Chapter 07: Linked Lists
Bag Implementations that Use Arrays
A List Implementation That Links Data
Presentation transcript:

Linked Bag Chapter 3

Outline Pros and cons of ArrayBag Links and linked structures Class Node private class Node LinkedBag Methods Pros and cons of LinkedBag

Pros and Cons of ArrayBag quick, direct access to known positions fast add/remove at end of array Cons fixed size or cost of copying entries slightly slower remove in middle wasted space

Alternative to Arrays Each entry remembers who’s next bag itself remembers who’s first Known as a “chain” Fencer Architect Business Man (no one) Golfer Doctor

Adding to the Chain New guy remembers who was first bag remembers the new person Fencer Doctor Architect Business Man (no one) Golfer Professor Doctor

Removing from the Chain From front is easy reverse adding at front Fencer Doctor Architect Business Man (no one) Golfer Professor Doctor

Removing from the Chain From middle is harder find person remembering guy leaving have them remember the one after the person leaving Fencer Architect Fencer Business Man (no one) Golfer Doctor

Chains: Why? How? Don’t need a whole array of spaces one extra space for each object in the bag to remember who comes next But the objects don’t have extra space for remembering the following object! would require an extra instance variable can’t add an extra instance variable to a String (e.g.) we need some help – a little helper class

Minions Minions remember a person and a minion Gru remembers which minion comes first

Class Node (Our “Minion”) Remembers one object and one node must be able to remember any sort of object generic class next node remembers same kind of thing public class Node<T> { private T data; private Node<T> next; … } a Node & another Node & some data more data

Class LinkedBag (Our “Gru”) Remembers which Node comes first first node remembers the kind of thing that’s in the bag (same parameter) public class LinkedBag<T> { private Node<T> first; private int numEntries; … } a LinkedBag & 4 a Node & some data

LinkedBag Constructor Bag starts empty no first entry, zero entries public LinkedBag() { first = null; numberOfEntries = 0; } NOTE: no memory allocation no need to worry about partially initialized objects! no need for checkInitialization

Linked Bag Bag with doctor, architect, golfer and fencer & 4 & & & & /

Following the Chain curNode keeps track of where we are start at first minion/node (curNode = first) go to next minion/node (curNode = curNode.next) we know how many minions/nodes there are & 4 & & & & / curNode / &

Minions at Risk Clients should not be able to access Nodes could accidentally/maliciously change values curNode.next = myBag.getFirst(); & 4 & & & & / curNode /

Private Classes One class can actually belong to another Node can belong to LinkedBag Can be public or private private  only owner class can use it owner gets full access either way! Declare owned class inside owner class public class Owner { private class Owned {

Owned Generic Classes Don’t need <T> on owned class owner is already <T>, so owned is, too! public class LinkedNode<T> { private class Node { private T data; // same type as bag’s base type private Node next; … } private Node first; private int numberOfEntries;

Node Constructors Will need to create new nodes data filled in, next maybe filled in (null if not) code goes inside Node class inside LinkedBag public Node(T value) { this(value, null); } public Node(T value, Node n) { data = value; next = n;

Add an Entry First add: Second (and later) add: / “First” / & & 1 & / “First” / & & 1 & / “Later” “First” & 2 & 1 & 1 & / &

add(T) Method LinkedBag method (not a Node method!) create Node to remember new data value its next field is whatever was first even if there was nothing in the bag (first == null) public boolean add(T newData) { first = new Node(newData, first); ++numberOfEntries; return true; }

toArray() Method Need to make a new array & copy values need to follow the trail of minions public T[] toArray() { T[] result = (T[]) new Object[numberOfEntries]; currentNode = first; for (int i = 0; i < numberOfEntries; ++i) { result[i] = currentNode.data; currentNode = currentNode.next; } return result;

Testing Core Methods Tests for LinkedBag are exactly the same as for ArrayBag same methods; same behaviour expected replace new ArrayBag with new LinkedBag should get same results

getCurrentSize() Method Return the number of entries public int getCurrentSize() { return numberOfEntries(); } we could count the number of entries what would that code look like? but why bother? & 4

isEmpty() Method Two versions numberOfEntries is zero: first is null: public boolean isEmpty() { return numberOfEntries == 0; } first is null: return first == null; /

getFrequencyOf(T) Method Loop thru Nodes counting those equals public int getFrequencyOf(T anEntry) { Node curNode = first; int count = 0; for (int i = 0; i < numberOfEntries; ++i) { if (curNode.data.equals(anEntry)) { ++count; } curNode = curNode.next; return count;

contains(T) Method Loop thru until find data or end of bag public int getFrequencyOf(T anEntry) { Node curNode = first; for (int i = 0; i < numberOfEntries; ++i) { if (curNode.data.equals(anEntry)) { return true; } curNode = curNode.next; return false;

remove() Method Reverse add method to remove first entry possible problem: nothing in bag public T remove() { if (first != null) { Node toDelete = first; first = toDelete.next; --numberOfEntries; return toDelete.data; } return null; toDelete & “One” “Two” & 1 & 4 & 1 & & 3

clear() Method Same as before! keep removing until bag is empty public void clear() { while (!isEmpty()) { remove(); }

remove(T) Considerations Remove node by updating links links to update in node before the one with data find the node before the node with the data but the data might not be there but the data might be in the first node actually, we already know how to do the first node… hmm. & & & / removing the Golfer Node before Golfer needs to change link

remove(T) Clever Plan Find the node with the desired data Swap in the data from the first position Remove the first node using remove() & 4 & & & & / curNode &

remove(T) Method what if the node with the data is the first node? public boolean remove(T anEntry) { Node curNode = findNode(anEntry); // private method if (curNode != null) { curNode.data = first.data; remove(); // updates numberOfEntries return true; } return false; what if the node with the data is the first node?

findNode(T) Method Returns the node with the wanted data returns null if the data wasn’t found private Node findNode(T anEntry) { Node curNode = first; for (int i = 0; i < numberOfEntries; ++i) { if (curNode.data.equals(anEntry)) { return curNode; } curNode = curNode.next; return null;

Exercise Easy: Harder: Rewrite contains to use findNode Why can’t frequencyOf use findNode? How could we change findNode so it could? What changes would we need to make to remove(T) and contains(T) if we did? Rewrite frequencyOf with the new findNode

Pros & Cons of LinkedBag quick, direct access to first position fast add/remove at front of bag little/no copying cost grows and shrinks as required Cons slightly slower remove in middle chain requires more memory than array (!)

ArrayBag vs. LinkedBag Linked grow smoothly; Array in jumps Linked shrinks smoothly; Array doesn’t Linked uses more memory Linked slightly slower to search following links slower than incrementing index Add quick in both Remove quick when removing last added

Next Time How do we tell what’s better?