Document 11586318

advertisement
1.00 Tutorial 9
Outline
• Quiz 2 results
• PS#8
• Linked lists & iterators
Quiz 2 Results
• Average:
• Std dev:
• n:
84
12
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
SLink
SLink
SLink
next
obj
next
obj
next
obj
Object 2
Object 3
Object 1
class SLinkedList {
SLink head;
//add, delete, isEmpty, etc.;
}
class SLink {
SLink next;
Object obj;
}
null
Linked List Example 2: Customized
• Link and data are combined into one class
• Less general, but easier to program
JavaStudent
JavaStudent
JavaStudent
next
next
next
name
name
name
…
…
…
class ListOfStudents {
JavaStudent head;
//add, delete, etc.
}
class JavaStudent {
JavaStudent next;
String name;
int[] quizGrades;
int[] psetGrades;
}
null
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
item
A
next
item
B
next
item
C
null
Linked List Problem
• And make it look like this:
next
item
A
next
item
B
next
item
C
next
item
A
next
item
B
next
null
item
C
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);
}
}
Download