Presentation is loading. Please wait.

Presentation is loading. Please wait.

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)

Similar presentations


Presentation on theme: "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)"— Presentation transcript:

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

2 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.

3 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.

4 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 notes throws NoSuchElementException; public Object removeFirst() throws NoSuchElementException; public void clear(); public int size(); public void print(); }

5 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.

6 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.

7 Singly Linked List Diagram List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

8 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.

9 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 ); } }...

10 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 );

11 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;

12 == 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 boolean objectEquals( Object a, Object b ) { if ( a == null ) return ( b == null ); else return a.equals( b ); } Not in our Link class

13 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.

14 removeFirst(), before List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

15 removeFirst(), after List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

16 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; }

17 removeFirst(), special case List firstlast Link 1 Item 1 null before List firstlast Link 1 Item 1 null after

18 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

19 removeLast(), before List firstlast Link 1 Item 1 Link 3 Item 2 Item 3 null Link 2

20 removeLast(), after List firstlast Link 1 Item 1 Link 3 Item 2 Item 3 null Link 2 tt xx null ret

21 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; } }

22 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++; }

23 addFirst(), before List firstlast Link 1 Item 1 Link n Item n... null

24 addFirst(), after List firstlast Link 1 Item 1 Link n Item n... null Link 0 Item 0

25 addFirst(), special case List firstlast Link 1 Item 1 null before List firstlast null after

26 Exercise Write addLast(): –Draw a picture of the list before and after –Handle the special case of a currently empty list

27 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++; }

28 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; }

29 Other methods public int size() { return length; } public boolean isEmpty() { return( first == null ); } public void clear() { first = last = null; length = 0; }

30 Exercise Write the print() method –Check if list is empty –Otherwise walk the list and print out each item

31 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; }

32 Main method public 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: ");

33 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); } }

34 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?

35 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

36 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

37 Linked List Example 1: General SLink next obj SLink next obj SLink next obj null Object 1Object 2Object 3 class SLinkedList { SLink head; //add, delete, isEmpty, etc.; } class SLink { SLink next; Object obj; }

38 Linked List Example 2: Customized Link and data are combined into one class Less general, but easier to program null JavaStudent 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 …


Download ppt "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)"

Similar presentations


Ads by Google