Upload
shonda-golden
View
222
Download
0
Tags:
Embed Size (px)
Citation preview
COMP 121COMP 121
Week 11: Linked ListsWeek 11: Linked Lists
ObjectivesObjectives
Understand how single-, double-, and Understand how single-, double-, and circular-linked list data structures are circular-linked list data structures are implementedimplemented
Understand the LinkedList classUnderstand the LinkedList class
Understand the Iterator interfaceUnderstand the Iterator interface
Understand the ListIterator interfaceUnderstand the ListIterator interface
Become familiar with another piece of the Become familiar with another piece of the Java Collection frameworkJava Collection framework
Linked ListLinked List
ArrayList: add/remove methods operate in linear ArrayList: add/remove methods operate in linear time O(n)time O(n) Require a loop to shift elements in the underlying Require a loop to shift elements in the underlying
arrayarray
LinkedList:LinkedList: Overcomes this by providing ability to add or remove Overcomes this by providing ability to add or remove
items anywhere in the list in constant time O(1)items anywhere in the list in constant time O(1) Each element (node) in a linked list stores information Each element (node) in a linked list stores information
and a link to the next, and, optionally, previous nodeand a link to the next, and, optionally, previous node
Single-Linked List NodeSingle-Linked List Node
A node contains a data item and one or more linksA node contains a data item and one or more links
A link is a reference to a nodeA link is a reference to a node
A node is defined inside of List class, making it an A node is defined inside of List class, making it an inner classinner class
The details of a node should be privateThe details of a node should be private
Single-Linked ListSingle-Linked List
Adding an ElementAdding an Element
Removing an ElementRemoving an Element
Single-Linked List - LimitationsSingle-Linked List - Limitations
Insertion at positions other than the first is O(n)Insertion at positions other than the first is O(n) Insertion at the front of the list is O(1)Insertion at the front of the list is O(1)
Can insert a node only after a referenced nodeCan insert a node only after a referenced node
Can remove a node only if we have a reference Can remove a node only if we have a reference to its predecessor nodeto its predecessor node
Can traverse the list only in the forward directionCan traverse the list only in the forward direction
Solution: double-linked listSolution: double-linked list
Double-Linked List NodeDouble-Linked List Node
Double-Linked ListDouble-Linked List
Adding an Element to a Double-Adding an Element to a Double-Linked List (Steps 1 and 2)Linked List (Steps 1 and 2)
Adding an Element to a Double-Adding an Element to a Double-Linked List (Steps 3 and 4)Linked List (Steps 3 and 4)
Removing an Element from a Removing an Element from a Double-Linked ListDouble-Linked List
Circular-Linked ListsCircular-Linked Lists
Links the last node of a double-linked list to the Links the last node of a double-linked list to the first node and the first to the lastfirst node and the first to the last
Advantages:Advantages: Can traverse in forward or reverse direction even after Can traverse in forward or reverse direction even after
you reach the last or first nodeyou reach the last or first node Can visit all list elements from any starting pointCan visit all list elements from any starting point Can never fall off the end of a listCan never fall off the end of a list
Disadvantage:Disadvantage: If not careful, can cause an infinite loop!If not careful, can cause an infinite loop!
Circular Linked ListCircular Linked List
The The LinkedList<E>LinkedList<E> Class Class
Part of the Java APIPart of the Java API
Implements the Implements the List<E>List<E> interface using a double-linked list interface using a double-linked list
The The Iterator<EIterator<E>> Interface Interface
The interface Iterator is defined as part of The interface Iterator is defined as part of API package API package java.utiljava.utilThe List interface declares the method The List interface declares the method iterator()iterator(), which returns an , which returns an IteratorIterator object that will iterate over the object that will iterate over the elements of that listelements of that listAn An IteratorIterator does not refer to or point to does not refer to or point to a particular node at any given time, but a particular node at any given time, but points between nodespoints between nodes
The The Iterator<E>Iterator<E> Interface (cont’d) Interface (cont’d)
The ListIterator<E> InterfaceThe ListIterator<E> Interface
IteratorIterator limitations: limitations: Can only traverse the Can only traverse the ListList in the forward direction in the forward direction Provides only a remove methodProvides only a remove method Must advance an Must advance an IteratorIterator using your own loop if using your own loop if
starting position is not at the beginning of the liststarting position is not at the beginning of the list
ListIterator<E>ListIterator<E> is an extension of the is an extension of the Iterator<E>Iterator<E> interface that overcomes the interface that overcomes the above limitationsabove limitationsLike Like IteratorIterator, a , a ListIteratorListIterator should be should be thought of as being positioned between thought of as being positioned between elements of the linked listelements of the linked list
ListIteratorListIterator
The The java.util.ListIteratorjava.util.ListIterator Interface Interface
LinkedListLinkedList Methods that Return Methods that Return ListIteratorsListIterators
ListIterator vs. IndexListIterator vs. Index
nextIndexnextIndex returns the index value of the item returns the index value of the item that would be returned by a subsequent call to that would be returned by a subsequent call to next()next()
previousIndexpreviousIndex returns the index value of the returns the index value of the item that would be returned by a subsequent call item that would be returned by a subsequent call to to previous()previous()
listIterator(int index)listIterator(int index) is a method of is a method of the the LinkedList LinkedList class:class: Returns a Returns a ListIteratorListIterator whose subsequent call to whose subsequent call to next()next() will return the item at position will return the item at position indexindex
Case Study: Writing a Program to Maintain a Case Study: Writing a Program to Maintain a List of Homework AssignmentsList of Homework Assignments
When an assignment is assigned, add it to the When an assignment is assigned, add it to the list, and when it is completed, remove it. Keep list, and when it is completed, remove it. Keep track of the due date. The program should track of the due date. The program should provide the following services:provide the following services: Add a new assignmentAdd a new assignment Remove an assignmentRemove an assignment Provide a list of the assignments in the order they Provide a list of the assignments in the order they
were assignedwere assigned Find the assignment with the earliest due dateFind the assignment with the earliest due date
UML Class DiagramUML Class Diagram
Assignment
descriptiondueDate
compareTo()
HomeworkList
assignmentList
add()remove()
displayAssignments()findEarliest()
HomeworkListHomeworkList Class Class
import java.util.ListIterator;import java.util.ListIterator;import java.util.LinkedList;import java.util.LinkedList;public class HomeworkList public class HomeworkList {{ private LinkedList<Assignment> assignmentList;private LinkedList<Assignment> assignmentList;
public HomeworkList()public HomeworkList() {{ assignmentList = new LinkedList<Assignment>();assignmentList = new LinkedList<Assignment>(); } }
HomeworkListHomeworkList Class (cont’d) Class (cont’d)
public void add(Assignment assignment)public void add(Assignment assignment)
{{
assignmentList.addLast(assignment);assignmentList.addLast(assignment);
}}
public void remove(Assignment assignment)public void remove(Assignment assignment)
{{
assignmentList.remove(assignment);assignmentList.remove(assignment);
}}
HomeworkListHomeworkList Class (cont’d) Class (cont’d)
public void displayAssignments()public void displayAssignments() {{ String message;String message; int i = 1;int i = 1; for (Assignment assignment : assignmentList)for (Assignment assignment : assignmentList) {{ message = "Assignment #" + (i++) + message = "Assignment #" + (i++) + ":\n" + ":\n" + assignment.getDescription() + assignment.getDescription() + "\nDue date: " +"\nDue date: " + assignment.getDueDate();assignment.getDueDate(); System.out.println(message);System.out.println(message); }} }}
HomeworkListHomeworkList Class (cont’d) Class (cont’d)
public Assignment findEarliest() public Assignment findEarliest() {{ Assignment earliest = null;Assignment earliest = null; Assignment current;Assignment current; ListIterator<Assignment> iter = ListIterator<Assignment> iter = assignmentList.listIterator();assignmentList.listIterator(); if (iter.hasNext()) if (iter.hasNext()) {{ earliest = iter.next();earliest = iter.next(); while (iter.hasNext()) while (iter.hasNext()) {{ current = iter.next();current = iter.next(); if (current.compareTo(earliest) < 0) if (current.compareTo(earliest) < 0) { { earliest = current;earliest = current; }} }} } } return earliest;return earliest;}}
SummarySummary
A linked list consists of a set of nodes, each of which A linked list consists of a set of nodes, each of which contains its data and a reference to the next nodecontains its data and a reference to the next nodeLocating an item at a position indicated by an index in a Locating an item at a position indicated by an index in a linked list requires traversing the list from the beginning linked list requires traversing the list from the beginning until the item at the specified index is founduntil the item at the specified index is foundAn An IteratorIterator gives with the ability to access the items gives with the ability to access the items in a in a ListList sequentially sequentially The The ListIteratorListIterator interface is an extension of the interface is an extension of the IteratorIterator interface interfaceThe Java API provides the The Java API provides the LinkedListLinkedList class, which class, which uses a double-linked list to implement the uses a double-linked list to implement the ListList interface interface
Questions?Questions?