aiti lecture 19 linked list adapted from mit course 1.00 spring 2003 lecture 26 and tutorial note 9...
Post on 30-Mar-2015
214 Views
Preview:
TRANSCRIPT
AITI Lecture 19 Linked List
Adapted from MIT Course 1.00 Spring 2003
Lecture 26 and Tutorial Note 9
(Teachers: Please do not erase the above note)
The Java Collection Classes
• The java.util package contains implementations of many data structures that we are also going to discuss and implement in a simpler way in class.
• You are welcome to use the standard Java implementations in problem sets. They are more elaborate and abstract than the implementations we will develop.
• Learning how to implement a few data structures makes you more sophisticated in how you use all data structures.
Lists as an Abstract Data Type
A list is a collection of elements that has a particular order. – It can have arbitrary length.– You should be able to insert or delete an
element anywhere.– You should be able to go through the list in
order an element at a time.
A List Interface
public interface List { public boolean isEmpty(); public void addFirst( Object o ); public void addLast( Object o ); public boolean contains(Object o); public boolean removeLast() // Error in
notesthrows NoSuchElementException;
public Object removeFirst() throws NoSuchElementException; public void clear(); public int size(); public void print();}
List Implementation Stategies
• There are many ways to implement a list.• In array-based implementations like the Java Vector inserting an element at any place except the end of the list is very expensive because all the elements from the point of insertion until the end must be moved back to make room for the new entry. There is a similar problem with deletion.
• For this reason, lists frequently use a linked implementation.
Singly Linked Lists
• Linked lists are like freight trains.• Each item to be put on the list is contained in an
instance of a new type of object called the link corresponding to a freight car.
• In a singly linked list, the link not only contains the listed item, but it also points to the next item in the list as one freight car is coupled to the next.
• The last link in the list points to nothing.
Singly Linked List Diagram
List
first last
Link 1
Item 1
Link n
Item 2 Item n
... nullLink 2
Singly Linked Lists, 2
• The list object itself points to the link holding the first listed item, and often holds an additional reference to the last link of the list to make it easier to append items.
• We say that a link “contains” or “points to”, and the list instance “points” or “holds a pointer”. In Java these are all synonyms for holding a reference.
• So the link doesn't really contain the item. It simply holds a reference to the listed item.
• The last link holds a null reference in the field that points to the next element.
The Link Inner Class
public class SLinkedList implements List {private static class SLink{
Object item; SLink next;
SLink( Object o, SLink n ) { item = o; next = n; }
SLink( Object o ) { this( o, null ); }
}. . .
Generic vs. Typed Lists
• The List interface we have specified is general like the Java Vector class. It stores and retrieves Objects.
• If you are writing your own list class, and you know you will only be handling Strings, say, you can replace the Object fields with String fields. For example,
private static class SLink { String item; SLink next; SLink( String o, SLink n ) { item = o; next = n; } SLink( String o ) { this( o, null ); }}public void addFirst( String o );
The SLinkedList Data Members
• Only first is necessary.• last and length could be found by traversing
the list, but having these members and keeping them up to date makes the calls size() and addXXX() faster. Implementations vary on this point.
private int length = 0;private SLink first = null;private SLink last = null;
== vs the Object equals method
• contains( Object o ) and remove( Object o ) must search for Object o in the list. What does it means to find it?
• Must the list contain a reference to the identical object (==)? Or is it sufficient that the list contain a reference to an object that is equal but possibly distinct?
static private booleanobjectEquals( Object a, Object b )
{if ( a == null )
return ( b == null );else
return a.equals( b );}
Not in our Link class
Beware the Special Case
• The tricky part about implementing a linked list is not implementing the normal case for each of the methods, for instance, removing an object from the middle of the list.
• What's tricky is making sure that your methods will work in the exceptional and boundary cases.
• For each method, you should think through whether the implementation will work on – an empty list, – a list with only one or two elements,– on the first element of a list,
– on the last element of a list.
removeFirst(), before
List
first last
Link 1
Item 1
Link n
Item 2 Item n
... nullLink 2
removeFirst(), after
List
first last
Link 1
Item 1
Link n
Item 2 Item n
... nullLink 2
removeFirst()
public Object removeFirst()throws NoSuchElementException
{ if ( first == null ) // if list is empty throw new NoSuchElementException(); else { SLink t = first; first = first.next;
// if list had 1 element and is now empty if ( first == null ) last = null; length--; return t.item; }}
removeFirst(), special case
List
first last
Link 1
Item 1
null
before
List
first last
Link 1
Item 1
null
after
Exercise
• Write removeLast()– Draw pictures of the list before and after
removing the last element– Handle the special cases where the list
currently has:• No elements• One element
removeLast(), before
List
first last
Link 1
Item 1
Link 3
Item 2 Item 3
nullLink 2
removeLast(), after
List
first last
Link 1
Item 1
Link 3
Item 2 Item 3
nullLink 2
t t
x xnull
ret
Solution public Object removeLast() throws NoSuchElementException { if (first == null) throw new NoSuchElementException(); else if (first == last) { // 1 element in list SLink t= first; first= last= null; length= 0; return t.item; } else { SLink t= first; while (t.next != last) t= t.next; Object ret= last.item; last= t; t.next= null; length--; return ret; } }
addFirst(Object o)
public void addFirst(Object o){ if ( first == null ) // if the list is empty { first = last = new SLink( o ); } else { first = new SLink( o, first ); }
length++;}
addFirst(), before
List
first last
Link 1
Item 1
Link n
Item n
... null
addFirst(), after
List
first last
Link 1
Item 1
Link n
Item n
... nullLink 0
Item 0
addFirst(), special case
List
first last
Link 1
Item 1
null
before
List
first last
null
after
Exercise
• Write addLast():– Draw a picture of the list before and
after– Handle the special case of a currently
empty list
Solution
public void addLast(Object o) { // if the list is empty if ( first == null ) first = last = new SLink( o ); else last = last.next = new SLink( o ); length++; }
contains()
public boolean contains(Object o) { boolean found= false; if (first == null) return false; SLink t= first; while (t != null) { if (objectEquals(t.item, o)) { found= true; break; } t= t.next; } return found; }
Other methods
public int size() { return length; } public boolean isEmpty() { return( first == null ); }
public void clear() { first = last = null; length = 0; }
Exercise
• Write the print() method– Check if list is empty– Otherwise “walk” the list and print out
each item
Solution
public void print() { if (first== null) { System.out.println("List is empty "); return; } SLink t= first; System.out.println("List contains: "); while (t != null) { System.out.print(t.item + " "); t= t.next; } System.out.println(); return; }
Main methodpublic class ListMain { public static void main(String[] args) { SLinkedList a= new SLinkedList(); while (true) { String text= JOptionPane.showInputDialog("Enter
1-addFirst, 2-addLast, 3-removeFirst, 4-removeLast, 5-contains, 6-quit: ");
int action= Integer.parseInt(text); if (action == 6) break; if (action== 1 || action== 2) text= JOptionPane.showInputDialog("Enter
string to store in list: ");
Main method, p.2
if (action == 5) text= JOptionPane.showInputDialog("Enter string
to find "); if (action == 1) a.addFirst(text); else if (action == 2) a.addLast(text); else if (action == 3) a.removeFirst(); else if (action== 4) a.removeLast(); else System.out.println("List has " + text + " ? " +
a.contains(text)); a.print(); } System.exit(0); } }
Linked List Uses and Variations
• Since our List interface possesses appendLast() and removeFirst() methods you can implement a trivial queue on top of the SLinkedList concrete data type.
• How would the implementation be changed if each link had a back reference (previous) as well as a forward reference (next)? Such lists are called (you guessed it) doubly linked lists. What operations become easier?
Linked List Summary
• Linked list double ended queue– Implementation as SLink and SLinkedList
classes• SLink class is inner class of SLinkedList
• Can implement stacks, queues, trees as linked lists or arrays
Review - 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 lists
Linked List Example 1: General
SLinknext
obj
SLinknext
obj
SLinknext
obj
null
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
…
class ListOfStudents {
JavaStudent head;
//add, delete, etc.
}
class JavaStudent {
JavaStudent next;
String name;
int[] quizGrades;
int[] psetGrades;
}
JavaStudent
next
name
…
JavaStudent
next
name
…
top related