CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.

Slides:



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

Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
DATA STRUCTURES USING C++ Chapter 5
Linked Lists Linear collections.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Double-Linked Lists and Circular Lists
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
CS 106 Introduction to Computer Science I 04 / 30 / 2007 Last lecture :( Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
Ordered Containers Cmput Lecture 21 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
1 Lecture 24 ADT Part V (Linked List Using Iterator) Overview  Utility Classes.  List Iterator.  View of the List Iterator.  Adding to the Head of.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
1 Collections Working with More than One Number or Data Type or Object.
Cmput Lecture 15 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from the book:
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
Chapter 3: Arrays, Linked Lists, and Recursion
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Ordered Containers CMPUT Lecture 19 Department of Computing Science University of Alberta ©Duane Szafron 2003 Some code in this lecture is based.
LinkedList Many slides from Horstmann modified by Dr V.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fifteen: An Introduction to Data Structures.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. An Introduction to Data Structures.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
(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.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
COSC 1P03 Data Structures and Abstraction 5.1 Linear Linked Structures A bank is a place where they lend you an umbrella in fair weather and ask for it.
Chapter 16 Data Structures 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 16 An Introduction to Data Structures.
Lecture Objectives  Linked list data structures:  Singly-linked (cont.)  Doubly-linked  Circular  Implementing the List interface as a linked list.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
COM S 228 Collections and Iterators Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff 201.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
Chapter 15 An Introduction to Data Structures. Chapter Goals To learn how to use the linked lists provided in the standard library To be able to use iterators.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
List Interface and Linked List Mrs. Furman March 25, 2010.
Recursive Objects (Part 2) 1. Adding to the front of the list  adding to the front of the list  t.addFirst('z') or t.add(0, 'z') 2 'a' 'x' LinkedList.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
CS-2852 Data Structures LECTURE 5 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 15 – An Introduction to Data Structures.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Data.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
Recursive Objects Singly Linked List (Part 2) 1. Operations at the head of the list  operations at the head of the list require special handling because.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Chapter 3: Fundamental Data Structures: The Array and Linked Structures Data Structures in Java: From Abstract Data Types to the Java Collections Framework.
4. Linked Lists.
Chapter 20 An Introduction to Data Structures
Chapter 16 – Basic Data Structures
Introduction to Data Structures
Chapter 15 – An Introduction to Data Structures
Linked Lists.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
CSC 143 Java Linked Lists.
Data Structures & Algorithms
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
Presentation transcript:

CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost

2 Lecture Outline Data Structures Linked List Iterators

3 Arrays The shortcomings Fixed size Insertion into the middle of a contiguous array Removal from the middle of a contiguous array

4 Data Structures Objects whose purpose is to organize data (primitives or other objects) Allow us to store large amounts of information when it is not desirable to do so with an array Can grow and shrink as needed Can be more efficient to search than arrays in certain cases

5 Data Structures Java Libraries Java provides several data structures in its libraries  Contained in the java.util package [ To the JavaDoc, Batman! ] In the next few weeks we will be exploring some of these Data Structures and learning their strengths and weaknesses  When it is appropriate to use a particular structure

6 Linked Lists One of the most basic data structures is the linked list A linked list is a data structure which consists of a number of nodes, each of which has some contents and a reference to the next node (storage) List Node

7 Linked Lists Code View A linked list is a data structure which consists of a number of nodes (instances of a Node class), each of which has some contents (instance variable) a reference to the next node (instance variable) Object storage; Node next; class Node Object storage; Node next; Object storage; Node next; class SinglyLinkedList Node head;

8 Linked Lists vs. Arrays Adding and removing elements in the middle of a linked list is efficient Visiting the elements of a linked list in sequential order is efficient Random access is not efficient Lists can grow arbitrarily large  (Resizing is efficient)

9 Linked Lists Implementation To keep it simple, we will look at implementing a singly-linked list  Called “Singly Linked” because Node s only know about the Node after them (References, or links only go in one direction)  You will be asked to implement a Doubly Linked List in Lab 4

10 Linked Lists Implementation Node class  Holds a reference to the next Node  Holds a reference to the Object it is storing SinglyLinkedList class  Holds a reference head to the first node (storage) List Node

11 Lists In Code public class Node { Object contents; Node nextNode; public Node (Object contents) { this.contents = contents; } public class SinglyLinkedList { Node head; public SinglyLinkedList () { this.head = null; }

12 Adding a New First Element When a new Node is added to the list  It becomes the head of the list  The old list head becomes its next Node public class SinglyLinkedList { //... public void addFirst (Object add) { Node newNode = new Node(add); newNode.next = this.head; this.head = newNode; } }

13 Removing the First Element When the first element is removed  The data of the first node are saved and later returned as the method result  The successor of the list head becomes the list head  The old node will be garbage collected when there are no further references to it

14 Removing the First Element The removeFirst method public class SinglyLinkedList { //... public Object removeFirst() { if (head == null) return null; Object obj = this.head.contents; this.head = this.head.next; return obj; } }

15 Getting an Element by Index The getNth method public Object getNth (int index) { Node search = this.head; for (int i=0; i<index; i++) { if (search == null) return null; search = search.next; } return search.contents; }

16 Iterating Over Data Structures Iterating over a Linked List  We could just use a regular for loop: But what is this doing internally? [ Example on Board ]  Very inefficient for (int i=0; i<list.getSize(); i++) { Object nth = list.getNth(i);... // Do something with ‘nth’ }

17 Iterators Helpers for Stepping through Data Structures Let’s define a way for users to iterate through our data structure (SinglyLinkedList), one element at a time  Internal Iterator [ Example on Board ] But what if multiple different entities want to iterate over the Data Structure?  Position is invalidated for other users

18 Iterators Safely Exporting State What we need is a way to encapsulate (package up) and export a position in the Data Structure…  Allow multiple different simultaneous iterators over the Data Structure  We need to have a trusted way of providing a reference to our internal representation Exporting our internal representation How is this done?

19 Levels of Encapsulation Exporting State Safely We want the internal structure ( Node s) of the linked list to be as protected as possible We want to be able to export some notion of a position within the list  The easiest way to do this would be a reference to a Node But we don’t want to expose the Node object itself  Write an encapsulation for the behavior we want to export

20 Packages and Access Modifiers Classes that Work Together Closely Put our SinglyLinkedList, our Node, and our ListIterator classes inside of package Declare Node head in SinglyLinkedList with the protected access modifier ListIterator can access protected fields of the List, because List and ListIterator are in the same package Make the constructor of ListIterator protected so that it must be created via the SinglyLinkedList

21 Inner Classes In Java, we can define inner classes to encapsulate a subset of behavior  Helper objects Instances of inner classes can access all members of the class inside which they are defined (even private ones!) Preserves a clear division of functionality  Purpose of outer object does not become cluttered Allows us to define “trusted” ways to export an object’s state Enables programmers to use multiple instances of helper objects

22 Iterators ListIterator type  Gives access to elements inside a linked list  Encapsulates the concept of a ‘position’ anywhere inside the linked list  Protects the internal structure of the linked list while giving access

23 A List Iterator

24 List Iterator Think of an iterator as pointing between two elements in a data structure  Analogy: like the cursor in a word processor points between two characters The iterator method of the SinglyLinkedList class gets a new ListIterator  Points to the beginning of the list SinglyLinkedList employeeNames = new SinglyLinkedList(); ListIterator iterator = employeeNames.iterator();

25 A Conceptual View of a List Iterator

26 List Iterator Initially, the iterator points before the first element hasNext returns true if there is a next element The next method moves the iterator and returns the current item Object next = iterator.next(); if (iterator.hasNext()) iterator.next();

27 List Iterator The next method returns the element that the iterator is passing while (iterator.hasNext()) { Object obj = iterator.next(); // Do something with obj }

28 LinkedListIterator The LinkListIterator class package listutil; public class LinkedListIterator { Node previous, position; List list; public LinkedListIterator(List list) { this.list = list; this.position = null; this.previous = null; } }

29 Linked List Iterator hasNext Method The next method should only be called when the iterator is not at the end of the list  If hasNext returns true The iterator is at the end if…  the list is empty ( list.head == null )  there is no element after the current position ( position.next == null )

30 The Linked List Iterator hasNext Method private class LinkedListIterator { //... public boolean hasNext() { if (position == null) return (list.head != null); else return (position.next != null); } //... }

31 The Linked List Iterator next Method position: reference to the last visited Node previous: reference to the Node before position next method: position reference is advanced to position.next Last position is remembered in previous If the iterator points before the first element of the list, then the previous is null and position must be set to list.head

32 The Linked List Iterator next Method public Object next() { if (!hasNext()) return null; previous = position; // Remember for remove if (position == null) position = list.head; else position = position.next; return position.contents; }

33 The Linked List Iterator remove Method If the element to be removed is the first element, call list.removeFirst Otherwise, the node preceding the element to be removed needs to have its next reference updated to skip the removed element

34 The Linked List Iterator remove Method public void remove() { if (previous == position) return; // Invalid state! if (position == list.head) { list.removeFirst(); } else { previous.next = position.next; } position = previous; }

35 Removing a Node From the Middle of a Linked List

36 The Linked List Iterator remove Method: Caveats If the previous equals position :  Then the call to remove does not immediately follow a call to next  Method cannot execute properly (throw an IllegalArgumentException)  It is illegal to call remove twice in a row  remove sets the previous reference to position

37 The Linked List Iterator set Method Changes the data stored in the previously visited element The set method public Object set (Object obj) { Object contents = null; if (position != null) { contents = position.contents; position.contents = obj; } return contents; }

38 The Linked List Iterator add Method add inserts the new node after the current position The most complex operation is the addition of a node Sets the successor of the new node to the successor of the current position

39 The Linked List Iterator's add Method public void add(Object obj) { if (position == null) { list.addFirst(obj); position = list.head; previous = null; } else { Node newNode = new Node(obj); newNode.next = position.next; position.next = newNode; previous = position; position = newNode; } }

40 Adding a Node to the Middle of a Linked List

41 Conclusion Lab 3 assigned today  Arrays & Iteration  Lab 2 due by midnight  I will be in lab now