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

Slides:



Advertisements
Similar presentations
Inserting a Node into a Specified Position of a Linked List To create a node for the new item newNode = new Node(item); To insert a node between two nodes.
Advertisements

Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-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.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Linked Lists part II. Linked Lists A linked list is a dynamic data structure consisting of nodes and links: 627 start 8 This symbol indicates a null reference.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
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.
Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 1 Principles for implementing ADTs ADT operations as “walls” between.
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.
List Interface and Linked List Mrs. Furman March 25, 2010.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
1 CS162: Introduction to Computer Science II Abstract Data Types.
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.
1 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Jung Soo (Sue) Lim Cal State LA.
Chapter 16: Linked Lists.
C++ Programming:. Program Design Including
The List ADT.
EECE 310: Software Engineering
Data Structure By Amee Trivedi.
The List ADT Reading: Textbook Sections 3.1 – 3.5
4. Linked Lists.
Lectures linked lists Chapter 6 of textbook
Linked Lists Chapter 5 (continued)
UNIT-3 LINKED LIST.
EEL 4854 IT Data Structures Linked Lists
Queues Queues Queues.
Programming Abstractions
LINKED LISTS CSCD Linked Lists.
Top Ten Words that Almost Rhyme with “Peas”
Introduction to Data Structures
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Linked Lists.
Topic 11 Linked Lists -Joel Spolsky
Arrays and Linked Lists
Chapter 18: Linked Lists.
Programming in Java Lecture 11: ArrayList
The List ADT Reading: Textbook Sections 3.1 – 3.5
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
CS212D: Data Structures Week 5-6 Linked List.
Programming Abstractions
Dynamic Data Structures and Generics
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Doubly Linked List Implementation
Linked Lists The items in a linked list data structure are linked to one another An item in a linked list references its successor A linked list is able.
Collections Framework
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Lecture 16 Section 6.2 Thu, Mar 1, 2007
Dynamic Data Structures and Generics
Lecture 14 Linked Lists CSE /26/2018.
Linked Lists Chapter 5 (continued)
CSC 143 Java Linked Lists.
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
General List.
Programming II (CS300) Chapter 07: Linked Lists
Linked Lists Chapter 5 (continued)
Topic 11 Linked Lists -Joel Spolsky
Presentation transcript:

Programming II (CS300) Chapter 07: Linked Lists and Iterators Mouna KACEM mouna@cs.wisc.edu Fall 2018

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

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

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

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

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

Implementation of the ListADT /** * LinkedList class represents a reference-based implementation of ADT list. * @author <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

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

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

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

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

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

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

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

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

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

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

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

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

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: 0 1 2 3 4 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

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: 0 1 2 3 4 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

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: 0 1 2 3 4 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

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: 0 1 2 3 4 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

Implementation of the ListADT public void add(int index, T newObject); Case3: 0 < index < list.size() newNode: runner: Index: 3 indices: 0 1 2 3 4 5 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

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

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

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

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

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

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()

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:

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

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: 0 1 2 3 4 3 18 -5 78 10 head: X 35 runner: a pointer of type LinkedNode<T> used to traverse the list

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

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: 0 1 2 3 4 18 -5 X 78 10 head: 35 3 runner: a pointer of type LinkedNode<T> used to traverse the list

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

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

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

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: https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html */ }

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?

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?

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 https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html 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

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 https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html

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

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

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:

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:

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

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