Linklist21 Linked Lists II The rest of the story.

Slides:



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

Linked Lists Geletaw S..
Why not just use Arrays? Java ArrayLists.
Stacks, Queues, and Linked Lists
DATA STRUCTURES USING C++ Chapter 5
CSC211 Data Structures Lecture 9 Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
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.
queues1 Queues Data structures that wait their turn.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than.
Chapter 3 Collection Classes Anshuman Razdan Department of Engineering
CHAPTER 8 Lists. 2 A list is a linear collection Adding and removing elements in lists are not restricted by the collection structure We will examine.
CSC212 Data Structure - Section FG Lecture 9 Linked Lists Instructor: Zhigang Zhu Department of Computer Science City College of New York.
@ Zhigang Zhu, CSC212 Data Structure - Section FG Lecture 10 The Bag and Sequence Classes with Linked Lists Instructor: Zhigang Zhu Department.
trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called.
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Lecture 6: Linked Lists Linked lists Insert Delete Lookup Doubly-linked lists.
Chapter 4 Linked Lists Anshuman Razdan Div of Computing Studies
Chapter 3: Arrays, Linked Lists, and Recursion
1 Linked Lists It’s a conspiracy!. 2 Linked list: a data structure used to represent an ordered list Consists of a sequence of nodes A node consists of.
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
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 7 Stacks II CS Data Structures I COSC 2006
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
Xiaoyan Li, CSC211 Data Structures Lecture 10 The Bag and Sequence Classes with Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 17: Linked Lists.
(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.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
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.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Chapter 5 Linked Lists II
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
CS2006- Data Structures I Chapter 5 Linked Lists III.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter 5 Linked Lists. © 2004 Pearson Addison-Wesley. All rights reserved 5 A-2 Preliminaries Options for implementing an ADT –Array Has a fixed size.
TreeBag a BST implementation. Example class - TreeBag  remember Bag?  collection of items, order does not matter  repeated items allowed public void.
Chapter 7 Queues Introduction Queue applications Implementations.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
CS162 - Topic #7 Lecture: Dynamic Data Structures –Review of pointers and the new operator –Introduction to Linked Lists –Begin walking thru examples of.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
“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.
CSCS-200 Data Structure and Algorithms Lecture
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Pointers and Linked Lists
Pointers and Linked Lists
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
Chapter 4 Linked Lists
Top Ten Words that Almost Rhyme with “Peas”
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Pointers and Linked Lists
Lists.
CSC 143 Java Linked Lists.
Programming II (CS300) Chapter 07: Linked Lists
Stacks, Queues, and Deques
Presentation transcript:

linklist21 Linked Lists II The rest of the story

Adding/removing in the middle of a list, part deux Up to now, we have performed operations on nodes in the middle of a list with a crucial assumption: we have an external reference to a node preceding the space we want to insert a new node, or the node we want to remove We need a way to create such an external reference linklist22

One approach One way to tackle the problem involves using three of the methods we have previously examined: listLength, listSearch and listPosition: –listSearch finds a target value in a list –listLength returns the number of Nodes in a list –listPosition returns a reference to a particular Node We can use these methods, along with the assumption that the data in our list are kept in order, to come up with the code on the next slide linklist23

Implementation of findPrevious linklist24 public static Node findPrevious (Node head, int target) { Node previous=null, cursor; if (head = null) return previous; for(cursor = head; cursor!=null && cursor.getData() < target; cursor = cursor.getLink()); if(cursor == null) previous = Node.listLocate(head, listLength(head)); else { int shortLen = listLength(cursor); previous = listLocate(listLength(head) – shortLen); } return previous; }

Copying a linked list You may have noticed that we didn’t choose to make the Node class implement Cloneable In terms of copying an entire list, this makes sense; again, a linked list is not a Node, but rather a collection of Nodes To make a copy of a list, we will employ another static method linklist25

How not to do it Because we always have a reference to a head pointer, it’s tempting to try copying a list using just the insertion technique we already know: Node newList = null; for (Node cursor = head; cursor != null; cursor = cursor.getLink()) newList = new Node (cursor.getData(), newList); linklist26

A better way The code on the previous slide will traverse the original list (referenced by head) and copy all of the nodes, but they will end up in reverse of their original order A better way involves using a tail pointer for the new list, adding each new node after the last node instead of before the first one The listCopy method is presented on the next slide linklist27

Code for listCopy linklist28 public static Node listCopy(Node source) { Node copyHead; Node copyTail; if (source == null) return null; copyHead = new Node(source.data, null); copyTail = copyHead; while (source.link != null) { source = source.link; copyTail.addNodeAfter(source.data); copyTail = copyTail.link; } return copyHead; }

Copying a list with a tail reference As mentioned before, it is sometimes useful to keep track of both the head and tail of a linked list Unfortunately, Java doesn’t permit us to have more than one return value from a method – or does it? Not really, but kind of – we can return an array from the method, and that array can contain multiple values linklist29

Copying list with tail reference linklist210 public static Node[ ] listCopyWithTail(Node source) { Node copyHead; Node copyTail; Node[ ] answer = new Node[2]; if (source == null) return answer; copyHead = new Node(source.data, null); copyTail = copyHead; while (source.link != null) { source = source.link; copyTail.addNodeAfter(source.data); copyTail = copyTail.link; } answer[0] = copyHead; answer[1] = copyTail; return answer; }

Copying part of a linked list Sometimes we only need a portion of a linked list, rather than a copy of the entire list The listPart method, shown on the next slide, handles this situation The two parameters, start and end, are references to the beginning and end of the part of the list we wish to copy linklist211

listPart method linklist212 public static Node[ ] listPart(Node start, Node end){ Node copyHead; Node copyTail; Node cursor; Node[ ] answer = new Node[2]; copyHead = new Node(start.data, null); copyTail = copyHead; cursor = start; // continued on next slide

listPart continued linklist213 while (cursor != end) { cursor = cursor.link; if (cursor == null) throw new IllegalArgumentException ("end node was not found on the list"); copyTail.addNodeAfter(cursor.data); copyTail = copyTail.link; } answer[0] = copyHead; answer[1] = copyTail; return answer; }

linklist214 Bag ADT using linked list Invariant: –Items are stored in a linked list of Nodes; member variable head refers to the beginning of the list –Member variable manyNodes stores the current size of the Bag (in # of nodes)

linklist215 List-based Bag vs. Array-based Bag In the list-based version of the Bag, most of the same methods are defined, but with different implementations An exception is the ensureCapacity method; since a linked list can grow and shrink easily (without the need to make a temporary copy of a data array) For this implementation, a new method is added for the heck of it: the grab() method returns a random value from the Bag’s contents

linklist216 Bag member methods Default constructor: creates empty bag Code: public Bag ( ) { head=null; manyNodes=0; }

linklist217 Clone() method Like the array-based bag, the linked list version implements the Cloneable interface, and thus must provide a clone() method Code shown on next slide

Clone method linklist218 public Object clone( ) { Bag answer; try { answer = (Bag) super.clone( ); } catch (CloneNotSupportedException e) { throw new RuntimeException ("This class does not implement Cloneable"); } answer.head = Node.listCopy(head); return answer; }

linklist219 Remove method Strategy is similar to removal of target value from an array With array, we copied the last index’s data into the slot occupied by the target value, then decremented used With linked list, we’ll copy the head Node’s data value into the target Node, then remove the head Node

linklist220 Code for remove method public boolean remove(int target) { Node targetNode; targetNode = Node.listSearch(head, target); if (targetNode == null) return false; else { targetNode.setData(head.getData( )); head = head.getLink( ); manyNodes--; return true; } }

linklist221 countOccurrences method Strategy: create local variable (cursor) that refers to a Node – use listSearch to find the target value, and assign its return value to cursor If cursor isn’t null, count one occurrence Continue process until cursor becomes null

linklist222 Code for countOccurrences public int countOccurrences(int target) { int answer = 0; Node cursor; cursor = Node.listSearch(head, target); while (cursor != null) { answer++; cursor = cursor.getLink( ); cursor = Node.listSearch(cursor, target); } return answer; }

linklist223 Add methods Since Bag is unordered ADT, follow path of least resistance and insert all items at front of list We follow this procedure for add(), addMany(), and addAll() (next several slides)

add method linklist224 public void add(int element) { head = new Node(element, head); manyNodes++; }

addMany method linklist225 public void addMany(int... elements) { for (int i : elements) add(i); }

addAll method linklist226 public void addAll(Bag addend) { Node[ ] copyInfo; if (addend.manyNodes > 0) { copyInfo = Node.listCopyWithTail(addend.head); copyInfo[1].setLink(head); head = copyInfo[0]; manyNodes += addend.manyNodes; } }

linklist227 The union method Creates a new Bag that is the union of two other bags Method is static so that it can be applied to any two Bag objects (and has no effect on either one)

linklist228 Code for union public static Bag union(Bag b1, Bag b2) { answer = new Bag( ); answer.addAll(b1); answer.addAll(b2); return answer }

linklist229 Grab method New function for Bag: grab pulls a random item out of the Bag for inspection Curiously, it doesn’t actually remove the item -- if you wanted to add this functionality, you’d have to add a call to the remove method

linklist230 Code for grab method public int grab( ) { int i; Node cursor; if (manyNodes == 0) throw new IllegalStateException("Bag size is zero"); i = (int)(Math.random( ) * manyNodes) + 1; cursor = Node.listPosition(head, i); return cursor.getData( ); }

linklist231 But wait, there’s more! Doubly-linked lists Singly-linked lists have one major limitation: you can only traverse the list in one direction A variation on the linked list: linking each node to its previous neighbor as well as its next neighbor makes bi-directional list traversal possible

linklist232 Modified class definition for doubly-linked list public class Node { private int manyItems; private Node link; // link to next Node private Node back; // link to previous Node … }

linklist233 Methods that must be modified constructor addNodeAfter remove

Constructors for doubly-linked list linklist234 public Node (int d, Node b, Node n) { data = d; back = b; link = n; } public Node ( ) { this (0, null, null); }

linklist235 addNodeAfter method Strategy is similar to singly-linked addNodeAfter, but with the additional complication that the node has two links Important thing to remember: make links before you break them!

linklist236 Code for add method public void addNodeAfter (Node previous, int entry) { Node n = new Node(entry, previous, null); n.link = previous.link; if (previous.link != null) previous.link.back = n; previous.link = n; }

linklist237 Linked Lists II The rest of the story