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.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
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.
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)
Concrete collections in Java library
Double-Linked Lists and Circular Lists
The List ADT Textbook Sections
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.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
COMP 121 Week 11: Linked Lists. Objectives Understand how single-, double-, and circular-linked list data structures are implemented Understand the LinkedList.
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.
Lists and Iterators CSC311: Data Structures 1 Chapter 6 Lists and Iterators Objectives Array Lists and Vectors: ADT and Implementation Node Lists: ADT.
15-Jun-15 Lists in Java Part of the Collections Framework.
Linked Lists CSC 172 SPRING 2004 LECTURE 6. ANNOUNCEMENTS Project 2 due Wed, Feb 18 th, 5PM, CSB Read Weiss Chapter 17 Department T shirts available $10.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Linked Lists CSC 171 FALL 2001 LECTURE 20 COURSE EVALUATIONS Tuesday, December 11 th, in Lecture.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
1 Collections Working with More than One Number or Data Type or Object.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Linked Lists CSC 172 SPRING 2004 LECTURE 6. ANNOUNCEMENTS Project 2 due Wed, Feb 18 th, 5PM, CSB Read Weiss Chapter 17 Department T shirts available $10.
Linked Lists. RHS – SOC 2 Linked lists We can already store collec- tions of objects in arrays and array lists – why would we need other data structures…?
The Java Collections Framework Chapters 7.5. Outline Introduction to the Java Collections Framework Iterators Interfaces, Abstract Classes and Classes.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
LinkedList Many slides from Horstmann modified by Dr V.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fifteen: An Introduction to Data Structures.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
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.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Using Iterators Trey Chandler Burlington Williams High School Mr. Langner’s Class,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Chapter 16 Data Structures 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 16 An Introduction to Data Structures.
COMP 121 Week 11: Linked Lists.
Lecture Objectives  Linked list data structures:  Singly-linked (cont.)  Doubly-linked  Circular  Implementing the List interface as a linked list.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 1 Principles for implementing ADTs ADT operations as “walls” between.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
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.
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.
Chapter 22 Generic Programming. Chapter Goals To understand the objective of generic programming To be able to implement generic classes and methods To.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
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 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Slides by Donald W. Smith
Chapter 5: The List Abstract Data Type
CSE 373 Implementing a Stack/Queue as a Linked List
Unit 1 Hadoop and big data
Chapter 20 An Introduction to Data Structures
Chapter 16 – Basic Data Structures
Linked Lists Chapter 6.5, 17 CSCI 3333 Data Structures.
Introduction to Data Structures
Linked Lists.
Chapter 15 – An Introduction to Data Structures
Computer Science and Engineering
Presentation transcript:

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 a Linked List.  Removing to the Head of a Linked List.  Removing a Link from the Middle of a Linked List.  Adding a Link to the Middle of a Linked List.  Example 1.  Example 2.  Preview:

2 Lecture 24 Iterator Interface  An Iterator is an interface that can be implemented by a collection class. The Iterator interface in java.util declares three methods. An Iterator object allows you to access all the objects it contains serially– but only once. There’s no way to go back to the beginning!!! MethodDescription next() Returns an object as type Object starting with the first, and sets the Iterator object to return the next object on the next call of this method. If there is no object to be returned the method throws NoSuchElementException exception. hasNext() Returns true if there is a next object to be retrieved by a call to next(). remove() Removes the last object returned by next() from the collection that supplied the Iterator object. If next() has not been called or if you call remove() twice after calling next(), an IllegalStateException will be thrown.

3 Lecture 24 ListIterator Interface The ListIterator interface provides methods for traversing the objects in a collection backward or forward !!! MethodDescription next() Retrieves the next object in sequence- the same as for the Iterator interface. hasNext() Returns true if there is an object that will be returned by next(). previous() Returns the previous object in sequence in the list. You use this method to run backwards through the list. hasPrevious() Returns true if the next call to previous() will return an object. previousIndex() Returns the index of the object that will be returned by the next call to previous(), or returns –1 if the ListIterator object is at the beginning.

4 Lecture 24 ListIterator Interface (Cont’d) MethodDescription remove()Removes the last object that was retrieved by next() or previous(). The UnsupportedOperation exception is thrown if the remove operation is not supported for this collection. add(Object obj)Adds the argument immediately before the object that would be returned by the next call to next(), and before the object that would returned by the next call to previous(). set(Object obj)Replaces the last object retrieved by a call to next() or previous(). If neither next() nor previous() have been called, or add() or remove() have been called most recently, a hasPrevious()Returns true if the next call to previous() will return an object previousIndex()Returns the index of the object that will be returned by the next call to previous(), or returns With a ListIterator you can add and replace objects, as well as remove them from the collection.

5 Lecture 24 ListIterator Interface (Cont’d) The LinkedList class in the java.util package implements linked lists. This linked list remembers both the first and the last link in the list. You have easy access to both ends of the list with the: void addFirst(object obj), void addLast(Object obj), Object get First(), Object removeFirst(), Object removeLast() The Java library supplies a ListIerator type. A list iterator encapsulates a position anywhere inside the linked list, think of the iterator as pointing between two links, just as the cursor in a word processor points between two characters. LinkedList Link Ali Link Hamed Link Fahad Link Saad Link Jameel

6 Lecture 24 View of the ListIterator Interface Think of the Iterator as pointing between two links,just as the cursor in a word processor points between two characters, each link element as being like a letter in a word processor, and think of the Iterator as being like the blinking cursor between letters. A H FS A H F S A J F H S

7 Lecture 24 /*Here is a sample program that inserts elements into a list and then iterates through the list, adding and removing elements. Finally, the entire list is printed. The commet indicate the iterator position*/ import java.util.LinkedList; import java.util.ListIterator; public class ListTest1 { public static void main(String[] args) { LinkedList staff = new LinkedList(); staff.addLast(“Ali"); staff.addLast("Hamed"); staff.addLast(“Fahad"); staff.addLast(“Saad"); // | in the comments indicates the iterator position ListIterator iterator = staff.listIterator(); // |AHFS iterator.next(); // A|HFS iterator.next(); // AH|FS Programming Example 1

8 Lecture 24 // add more elements after second element iterator.add("Jameel"); // AHJ|FS iterator.add(“Rami"); // AHJR|FS iterator.next(); // AHJRF|S // remove last traversed element iterator.remove(); // AHJR|S // print all elements iterator = staff.listIterator(); while(iterator.hasNext()) System.out.println(iterator.next()); } // End of main() method } // End of ListTest1 class Programming Example 1 (Cont’d)

9 Lecture 24 Adding to the Head of a Linked List class LinkedList { public void addFirst(Object obj) { Link newLink=new Link(); newLink.data =obj; newLink.next=first; first=newLink; } // End of addFirst() method } // End of LinkedList class Adding a Link to the Head of a Linked List first Link Ali data next Link Rami data next

10 Lecture 24 Removing from the Head of a Linked List Removing a Link from the Head of a Linked List LinkedList first Link Ali data next Link Rami data next class LinkedList { public Object removeFirst() { if (first == null) throw new NoSuchElementException(); Object obj = first.data; first=first.next; return obj; } // End of removeFirst() method } // End of LinkedList class

11 Lecture 24 Removing a Link from the Middle of a Linked List public class Iterator { public void remove() { if(position == first) removFist(); else { if(previous ==null) throw new IllegalStateException(); previous.next = position.next; position = previous; } previous = null; } // End of remove() method } // End of class Iterator Note: If the previous reference is null, then this call to remove does not immediately follow a call to next, and we throw an Illegal StateException. Otherwise, we set the successor of the previous element to its successor, thereby eliminating it. LinkedList first Link Ali data next Link Rami data next ListIterator previous position Link Fahad data next

12 Lecture 24 Adding a Link to the Middle of a Linked List public class Iterator { public void add(Object obj) { if(position == null) addFirst(obj); else { Link newLink = new Link(); newLink.data = obj; newLink.next = position.next; position.next = newLink; position = newLink; previous=null; } } } Note: You insert the new link after the current position, and set the successor of the new link to the successor of the current position. LinkedList first Link Ramidata next ListIterator previous position Link Fahaddata next Link Khaleddata next newLink Link Alidata next

13 Lecture 24 import java.util.NoSuchElementException; public class ListTest2 { public static void main(String[] args) { LinkedList staff = new LinkedList(); staff.addFirst(“Thamer"); staff.addFirst(“Rached"); staff.addFirst("Hamed"); staff.addFirst("Dhafer"); // | in the comments indicates the iterator position LinkedList.Iterator iterator = staff.listIterator(); // |DHRT iterator.next(); // D|HRT iterator.next(); // DH|RT // add more elements after second element iterator.add("Jameel"); // DHJ|RT iterator.add("Nawaf"); // DHJN|RT iterator.next(); // DHJNR|T Programming Example 2 // remove last traversed element iterator.remove(); // DHJN|T // print all elements iterator = staff.listIterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } // End of main() method } // End of ListTest2 class

14 Lecture 24 /* A linked list is a sequence of links with efficient element insertion and removal. */ class LinkedList { /** Constructs an empty linked list. */ public LinkedList() { first = null; } // End of constructor LinkedList() /** Returns the first element in the linked the first element in the linked list. */ public Object getFirst() { if (first == null) throw new NoSuchElementException(); return first.data; } // End of getFirst() method /** Removes the first element in the linked the removed element. */ public Object removeFirst() { if (first == null) throw new NoSuchElementException(); Object obj = first.data; first = first.next; return obj; } // End of removeFirst() method Programming Example 2 (Cont’d)

15 Lecture 24 /** Adds an element to the front of the linked obj the object to add. */ public void addFirst(Object obj) { Link newLink = new Link(); newLink.data = obj; newLink.next = first; first = newLink; } // End of addFirst() method /** Returns an iterator for iterating through this an iterator for iterating through this list. */ public Iterator listIterator() { return new Iterator(); } // End of listIterator() method private Link first; private class Link { public Object data; public Link next; } Programming Example 2 (Cont’d)

16 Lecture 24 public class Iterator { /** Constructs an iterator that points to the front of the linked list. */ public Iterator() { position = null; previous = null; } /** Moves the iterator past the next the traversed element. */ public Object next() { if (position == null) { position = first; return getFirst(); } else { if (position.next == null) throw new NoSuchElementException(); previous = position; // remember for remove position = position.next; return position.data; } } // End of next() method Programming Example 2 (Cont’d)

17 Lecture 24 /** Tests whether there is an element after the iterator true if there is an element after the iterator position. */ public boolean hasNext() { if (position == null) return first != null; else return position.next != null; } /** Adds an element before the iterator position and moves the iterator past the inserted obj the object to add. */ public void add(Object obj) { if (position == null) addFirst(obj); else { Link newLink = new Link(); newLink.data = obj; newLink.next = position.next; position.next = newLink; position = newLink; previous = null; } } // End of add() method Programming Example 2 (Cont’d)

18 Lecture 24 /** Removes the last traversed element. This method may be called only after a call to the next() method. */ public void remove() { if (position == first) removeFirst(); else { if (previous == null) throw new IllegalStateException(); previous.next = position.next; position = previous; } previous = null; } // End of remove() method. private Link position; private Link previous; } // End of inner class Iterator } // End of class LinkedList Programming Example 2 (Cont’d)