Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming II (CS300) Chapter 07: Linked Lists and Iterators

Similar presentations


Presentation on theme: "Programming II (CS300) Chapter 07: Linked Lists and Iterators"— Presentation transcript:

1 Programming II (CS300) Chapter 07: Linked Lists and Iterators
Mouna KACEM Fall 2018

2 Linked Lists Introduction Linked List Abstract Data Type
General Implementation of the ListADT Practice Examples Iterators Practice Example Keep in Mind

3 Introduction: General Linked List
This chapter introduces how to: Declare the Abstract Data Type (ADT) Linked List Define the most commonly Operations for General Linked Lists Implement a General Linked List The basic Linked List consists of a collection of connected, dynamically allocated nodes or items of the same type. 18 10 -5 78 linkedList null item next item next item next item next

4 Introduction: General Linked List
A linked list contains a collection of data items of the same type that are stored in different objects referred as nodes Each node consists of two fields: A data item field : stores or refers to the data value A reference to an object of the same type This reference is used to connect to the next node in the list node linkedList 18 -5 78 10 null item next item next item next item next data item Reference to the next node in the list

5 Introduction: General Linked List
public class LinkedNode<T>{ // Fields private T item; // item data field of any type T private LinkedNode<T> next; // reference to the next node in the list // Constructors ... // Methods } // end generic class LinkedNode node linkedList 18 -5 78 10 null item next item next item next item next data item Reference to the next node in the list

6 Linked List Abstract Data Type
T refers to AnyType public interface ListADT<T> { // List of Operations public void add(T newObject); public void add(int index, T newObject); public boolean contains(T findObject); public boolean isEmpty(); public int size(); public int indexOf(T findObject); public T get(int index); public T remove(int index); } // end ListADT generic interface

7 Implementation of the ListADT
/** * LinkedList class represents a reference-based implementation of ADT list. <author> */ public class LinkedList<T> implements ListADT<T> { private LinkedNode<T> head; // entry point reference to linked list of items of type<T> public LinkedList() { head = null; } // end default constructor * TODO Implementation of the interface ListADT declared methods } // end LinkedList class

8 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list Create a NewNode that contains newObject as item fieldI If the list is empty, insert the newNode at the head of the list Otherwise, insert the newNode at the end of the list

9 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list The list is empty 35 newNode: X head: item next

10 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list The list is empty newNode: head: 35 item next

11 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list The list is empty (summary diagram) newNode: 1 X 3 35 head: head: 2 item next

12 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: newObject: 35 item next runner: 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

13 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: 35 item next runner: 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

14 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: 35 item next runner: 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

15 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: X 35 item next runner: X 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

16 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: X 35 item next runner: X 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

17 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list List is not empty newNode: runner: 18 -5 78 10 head: 35 item next runner: a pointer of type LinkedNode<T> used to traverse the list

18 Implementation of the ListADT
public void add(T newObject); // inserts newObject at the end of the linked list The list is not empty (summary diagram) newNode: X 3 35 item next 1 2 runner: Traverse the list 3 X 18 -5 78 10 head: runner: a pointer of type LinkedNode<T> used to traverse the list

19 Implementation of the ListADT
public void add(int index, T newObject); Precondition: 0 ≤ index ≤ list.size() If index < 0 or index > size()  error (throw an exception or display an error message) Otherwise, create a newNode (instance of LinkedNode) that contains the newObject as item data field If index == 0  insert the newNode at the head of the list If index == size()  insert the newNode at the end of the list If index > 0 and index < size()  insert newNode in the middle of the list at the index position

20 Implementation of the ListADT
public void add(int index, T newObject); Case3: 0 < index < list.size() newNode: Index: 3 -3 item next runner: inx = 0 inx = 1 indices: 18 -5 78 10 head: 35 item next runner initialized to head : a pointer of type LinkedNode<T> used to traverse the list inx an integer initialized to 0 : the index of the node pointed by runner in the list

21 Implementation of the ListADT
public void add(int index, T newObject); Case3: 0 < index < list.size() newNode: Index: 3 -3 item next runner: inx = 1 inx = 2 indices: 18 -5 78 10 head: 35 item next runner initialized to head : a pointer of type LinkedNode<T> used to traverse the list inx an integer initialized to 0 : the index of the node pointed by runner in the list

22 Implementation of the ListADT
public void add(int index, T newObject); Case3: 0 < index < list.size() newNode: Index: 3 X inx == index -1 -3 item next runner: inx = 2 X indices: 18 -5 78 head: X 10 35 item next runner initialized to head : a pointer of type LinkedNode<T> used to traverse the list inx an integer initialized to 0 : the index of the node pointed by runner in the list

23 Implementation of the ListADT
public void add(int index, T newObject); Summary Diagram Case3: 0 < index < list.size() newNode: Index: 3 1 4 X Traverse the list until inx = index -1 -3 2 item next runner: 4 3 inx = 2 X indices: 18 -5 78 X 10 head: 35 item next runner initialized to head : a pointer of type LinkedNode<T> used to traverse the list inx an integer initialized to 0 : the index of the node pointed by runner in the list

24 Implementation of the ListADT
public void add(int index, T newObject); Case3: 0 < index < list.size() newNode: runner: Index: 3 indices: 18 -5 78 -3 10 head: 35 item next runner initialized to head : a pointer of type LinkedNode<T> used to traverse the list inx an integer initialized to 0 : the index of the node pointed by runner in the list

25 Implementation of the ListADT
If the list is empty return false Otherwise (list is not empty) define a runner (a reference to a LinkedNode object) to traverse the list and look for the first node whose data item matches with findObject initialize runner to the head of the list traverse the list looking for a much with findObject while runner != null && there is no match go to the next node in the list if the findObject is found return true if the list is entirely traversed without finding a match, return false public boolean contains(T findObject); runner: a pointer of type LinkedNode<T> used to traverse the list

26 Implementation of the ListADT
List not empty findObject: 10 is runner.getItem().equals(findObject)? No runner: 18 -5 10 78 head: 10 item next runner: a pointer of type LinkedNode<T> used to traverse the list

27 Implementation of the ListADT
List not empty Example findObject: 10 is runner.getItem().equals(findObject)? Yes runner: return true 18 -5 10 78 head: 10 item next runner: a pointer of type LinkedNode<T> used to traverse the list

28 Implementation of the ListADT
public int indexOf(T findObject); Initialize index of type int to -1 if list is empty return index Otherwise define a runner (a reference to a LinkedNode object) to traverse the list and look for the first node whose data item matches with findObject initialize runner to the head of the list and increment index traverse the list looking for a much with findObject while runner!= null && there is no match go to the next node in the list and increment index if the findObject is found return index if the list is entirely traversed without finding a match, return -1 runner: a pointer of type LinkedNode<T> used to traverse the list

29 Implementation of the ListADT
public T get(int index); if index < 0 or index > size()  error (throw an exception or return null) Otherwise if the list is empty return null Otherwise (list is not empty and index in the range of the list indices) define a runner (a reference to a LinkedNode object) to traverse the list looking for the node of index “index” initialize runner to the head of the list and inx of type int to 0 while inx < index go to the next node in the list (runner = runner.getNext()) and increment inx return runner.getItem() Precondition: 0 ≤ index < list.size() runner: a pointer of type LinkedNode<T> used to traverse the list

30 Implementation of the ListADT
public T remove(int index); if index < 0 or index > size()  error (throw an exception or return null) Otherwise if the list is empty return null Otherwise (list is not empty and index in the range of the list indices) We distinguish between three cases Case1: index == 0 : return the item at the head of the list, then remove the node at the head Case2: index == size() – 1: return the item at the tail (end) of the list and remove that node from the list Case3: Index > 0 and index < size() -1 : (remove a node from the middle of the list) return the item of the node at index position and remove the latter Precondition: 0 ≤ index < list.size()

31 Implementation of the ListADT
public T remove(int index); Case1: List not empty and index == 0 : remove the node at the head of the list remove the node at the head of the list 1 2 3 item = head.getItem(); head = head.getnext(); return item 1 item: 18 18 -5 78 head: X 10 35 2 2 head:

32 Implementation of the ListADT
public T remove(int index); Case2: List not empty and index > 0 and index == size -1 : remove the node at the end (tail) of the list To remove a node from the end of a list, we need a pointer to its previous node Use a runner to reach the node of index size -2 Initialize runner to head and inx of type int to 0 While inx < index – 1, go to the next node (runner = runner.getNext()) and increment inx item = runner.getNext().getItem(); remove the node at the end of the list: runner.setNext(null); return item 18 -5 78 10 head: 35 runner: a pointer of type LinkedNode<T> used to traverse the list

33 Implementation of the ListADT
public T remove(int index); Case2: List not empty and index > 0 and index == size -1 : remove the node at the end (tail) of the list Get the item at runner.getNext() and Remove runner.getNext() Return item 3 Index: 4 Traverse the list to reach the node of index index-1 2 1 item = runner.getNext().getItem(); item: 35 runner: 3 runner: 2 runner: 2 runner: 2 inx = 0 inx = 2 inx = 3 inx = 1 indices: 3 18 -5 78 10 head: X 35 runner: a pointer of type LinkedNode<T> used to traverse the list

34 Implementation of the ListADT
public T remove(int index); Case3: List not empty and index > 0 and index < size -1 : remove a node at the middle of the list To remove a node from the middle of list (at a given index), we need a pointer to its previous node Use a runner to reach the node of index index - 1 Initialize runner to head and inx of type int to 0 While inx < index – 1, go to the next node (runner = runner.getNext()) and increment inx item = runner.getNext().getItem(); remove the node at the position index the list: runner.setNext(runner.getNext().getNext()); return item 18 -5 78 10 head: 35 runner: a pointer of type LinkedNode<T> used to traverse the list

35 Implementation of the ListADT
public T remove(int index); Case3: List not empty and index > 0 and index < size -1 : remove a node at the middle of the list Get the item at runner.getNext() // remove runner.getNext() runner.setNext(runner.getNext().getNext()) return item 3 Index: 2 Traverse the list to reach the node of index index-1 2 1 runner: item = runner.getNext().getItem(); item: 78 runner: 2 3 inx = 0 inx = 1 3 indices: 18 -5 X 78 10 head: 35 3 runner: a pointer of type LinkedNode<T> used to traverse the list

36 Implementation of the ListADT
public T remove(int index); We note that the implementation for Case2 and Case3 is the same. Case2: List not empty and index > 0 and index == size -1 : remove the node at the end (tail) of the list Case3: List not empty and index > 0 and index < size -1 : remove a node at the middle of the list

37 Practice Examples Declare the ListADT<T> interface
Implement the generic LinkedNode<T> class Implement the linked list of Integers class public class LinkedList implements ListADT<Integer> Test the implementation Implement the generic linked list LList<T> class Test the LList class implementation considering different types T

38 Iterable Interface and Iterators
Collection<T> Interface Iterators Iterable Interface For-each loop

39 Collection Interface Generic Interface Collection<T>
The interface Collection<T> specifies methods for performing some basic operations on any collection of objects public interface Collection<E> implements Iterable { /* general operations that can be applied to various types of collections containing various types of objects * to explore the different operations defined in the interface Collection of Java.util, go to: */ }

40 Traverse a Collection of Objects
A collection of Objects of type T can be an array, an ArrayList, a linkedList, etc. Need to traverse a collection to print out every item in the collection for instance Is there a generic way to do it?

41 Traverse a Collection of Objects
How to traverse an array of Objects? use a for loop to iterate through all the array indices How to traverse a singly linked list of Objects? use a while loop in which you advance a pointer along the list Variety of traversal mechanisms! How to come up with a single generic method to traverse a collection that works for all kinds of collections that are stored in wildly different forms?

42 Generic Way to Traverse a Collection of Objects
The problem is solved by using iterators! Iterator an object that can be used to traverse a collection Iterators are defined by a parameterized interface named Iterator<T> @see Different types of collections have iterators that are implemented in different ways, but all iterators are used in the same way An iterator provides a good way to iterate over a generic set type

43 Iterable interface The Iterable interface is a generic interface of java.lang package. public interface Iterable<T> Iterable interface has one method to override Iterator<T> interator() returns an iterator over a set of elements of type T For more details, please visit

44 For each loop An object instance of a class that implements the java.lang.Iterable<T> interface can be target of the “for each” statement Syntax For (<ElementType> <variable> : <collection>){ <loop boby> // Does not have any effect on the value of <variable> reference } The Iterable interface provides a clean and elegant way to code the iteration functionality

45 Doubly Linked Lists The singly linked list does not efficiently support some important operations For instance, it is time consuming to go to the end of the list Singly linked lists cannot implement “retreat” method which allows one backward move at the time while traversing a list A doubly linked list allows bidirectional traversal by storing two links per node Each node now has two links (next and prev) prev item next node: -5

46 Doubly linked lists Searching and traversing the list can easily be performed in both directions Doubly linked lists allow to move up just as easily as down in the list to insert after as well as before a node at a given position (index) Insertion (add) and removal (remove) operations involve twice as many link changes as for a singly linked list. 78 18 -5 : tail head:

47 Circular Linked List In a circularly linked list, the last node’s next link references the first one in the list (i.e. the head of the list) The circular list is useful when we want searching to allow wraparound 18 -5 10 head:

48 Keep in Mind A linked list represents a collection (that may be empty) of connected, dynamically allocated nodes (known as linked nodes) A linked node of a singly linked list must contain a reference to a node of the same type. This reference is used to connect to the next node in the list To add a node at the middle of a singly linked list, we need a reference to the previous node We need a reference to the node at the prior position to the one that we want to insert To remove a node from a singly linked list other than the head of the list, we need a reference to the node prior to the node that we want to remove To remove an item or object that we don’t know the index, we can make use of the method indexOf which returns the position (index) of an item in the linked list

49 Keep in Mind Doubly linked list allows bidirectional traversal of the list A doubly linked node has two links: a reference to the next node and a reference to the previous node in the list Insertion and deletion operations are more easy with doubly linked lists, but ensure more link changes compared to a singly linked list Common error while implementing linked list operations: NullPointerException! Methods should not be allowed to access fields via a null reference


Download ppt "Programming II (CS300) Chapter 07: Linked Lists and Iterators"

Similar presentations


Ads by Google