Você está na página 1de 3

1.

00 Tutorial 9
Outline
? Quiz 2 results
? PS#8
? Linked lists & iterators
Quiz 2 Results
? Average: 84
? Std dev: 12
? n: 80 students
Problem Set 8
? Check 1.00 web site for code to read in text
from a file for PS#8 (Assignments link)
Linked List
? A simple way to collect a series of objects
? Each Object or link refers to the next
? Two examples: general and customized
Linked List Example 1: General
null
SLink
next
obj
SLink
next
obj
SLink
next
obj
Object 1 Object 2 Object 3
class SLinkedList {
SLink head;
//add, delete, isEmpty, etc.;
}
class SLink {
SLink next;
Object obj;
}
Linked List Example 2: Customized
? Link and data are combined into one class
? Less general, but easier to program
nullJavaStudent
next
name
?
JavaStudent
next
name
?
JavaStudent
next
name
?
class ListOfStudents {
JavaStudent head;
//add, delete, etc.
}
class JavaStudent {
JavaStudent next;
String name;
int[] quizGrades;
int[] psetGrades;
}
List Iterator
public interface ListIterator {
public boolean hasNext();
public Object next()
throws NoSuchElementException;
public void remove()
throws IllegalStateException;
public void add (Object o);
public void set (Object o)
throws IllegalStateException;
}
List Iterator (cont.)
? The ?current? object in a list iterator
1. When a list iterator just got created, where does
?current? point to? How about after the first time we called
the next() method?
2. After adding an object (a call to the add() method),
what happens to the ?current? pointer? How about after
removing an object (a call to the remove() method)?
These answers are on page 7 of the lecture note 26.
Linked List Problem
? Using the linked list classes given in Lecture
26 (List.java, ListIterator.java,
SLinkedList.java), write a method that
will add each element in the list to the end.
? i.e., take this list
next next next
null
A B C
item item item
Linked List Problem
? And make it look like this:
A B C
next next next
item item item
A B C
next next next
item item item
null
these have been added to the end
? The code you?ll need is on the MIT website
Linked List Problem
public class Tutorial9 {
public static void repeatElementsAtEnd(List list) {
// add your code here
}
public static void main(String[] args) {
List linkedList = new SLinkedList();
linkedList.addLast("Curtis Eubanks");
linkedList.addLast("Peilei Fan");
linkedList.addLast("Bharath Krishna");
linkedList.addLast("Elana Wang");
repeatElementsAtEnd(linkedList);
/* print out all list elements */
ListIterator i = linkedList.listIterator(); int n=0;
while (i.hasNext())
System.out.println("element "+(++n)+": "+i.next());
System.exit(0);
}
}

Você também pode gostar