SLIDE 2 13-2
11/19/2001 (c) 2001, University of Washington 13-7
Exercise
- Suppose we’ve got a list containing “Apple”, “Dell”,
“Compaq”, and “IBM” in that order. Delete “Compaq” from the list
Node head; // first node
11/19/2001 (c) 2001, University of Washington 13-8
Implementing Lists with Linked Lists
- First, let’s augment our node class with a constructor (for
convenience)
// Node for a simple list public class Node { Object item; // data associated with this node Node next; // next Node or null if none // construct new node with given data item and next node public Node(Object item, Node next) { this.item = item; this.next = next; } }
11/19/2001 (c) 2001, University of Washington 13-9
Collection Interface (review)
- Methods defined in interface Container
int size( ) – # of items currently in the collection isEmpty( ) – (size( ) == 0) boolean contains(Object o) – true of o.equals(element) for an element in the collection boolean add(Object o) – ensure that o is in the collection by adding it if needed; return true if collection altered; false if not. boolean addAll(Collection other) – add all elements in the other collection boolean remove(Object o) – remove a single instance of o from the collection; return true if something was actually removed void clear( ) – remove all elements Iterator iterator( ) – return an iterator object for this collection
11/19/2001 (c) 2001, University of Washington 13-10
List Interface (review)
- Additional methods defined in interface List
Object get(int pos) – return element at position pos boolean set(int pos, Object elem) – store elem at position pos boolean add(int pos, Object elem) – store elem at position pos; slide elements at position pos to size( )-1 up one position to the right boolean remove(int pos) – remove item at given position; shift remaining elements to the left to fill the gap int indexOf(Object o) – return position of first occurrence of o in the list, or
boolean equals(Object o) – true if o is another ArrayList that is element by element equal to this one
- Precondition for most of these is 0 <= pos < size( )
- We will implement a subset of these
11/19/2001 (c) 2001, University of Washington 13-11
List Data & Constructor
// Simple version of LinkedList for CSE143 lecture example class SimpleLinkedList implements List { // instance variables private Node head; // first node in the list, or null if list is empty … // construct new empty list public SimpleLinkedList( ) { head = null; }
11/19/2001 (c) 2001, University of Washington 13-12
Method add
- First cut: add new node to existing list
public boolean add(Object o) { // create new node to place at end of list Node newNode = new Node(o, null); // find end of list and place new node there Node p = head; while (_____________________) { _________________________ } p.next = newNode; return true; }