Professional Documents
Culture Documents
CS Lunch This Week
CS Lunch This Week
Angela Wang Study Away Experience at the University of Mannheim, Germany Thursday, April 5, 12:15 Kendade 307
<<interface>> List
<<abstract>> AbstractList
ArrayList
LinkedList
Linked List
Represent values in nodes Each node contains: A value A reference to the next node
60
-3
60
-3
Node
class Node { ! ! public Node (int value) {} ! ! public Node (int value, Node nextNode) {} ! ! public void setNext(Node nextNode) {} ! ! public Node getNext() {} public int getValue() {} public void setValue(int newValue) {} ! ! private int data; ! ! private Node next; }
60
-3
class Node<E> { ! ! public Node<E> (E value) {} ! ! public Node<E> (E value, Node<E> nextNode) {} ! ! public void setNext(Node<E> nextNode) {} ! ! public Node<E> getNext() {} public E getValue() {} public void setValue (E newValue) {}
! ! private E data; ! ! private Node<E> next; } Node<String> n1 = new Node<String>(b); Node<String> n2 = new Node<String>(a, n1);
Node Generic
n2
a
n1
b
tail head
a b c d
numElements = 4
Creating a List
LinkedList<String> list = new LinkedList<String>(); list.addFirst(d);
list
head=null tail=null numElements=0
Creating a List
LinkedList<String> list = new LinkedList<String>(); list.addFirst(d); list.addFirst(c);
list
head tail numElements=1 d
Creating a List
LinkedList<String> list = new LinkedList<String>(); list.addFirst(d); list.addFirst(c); public void addFirst(E value) { head = new Node<E> (value, head); if (tail == null) { tail = head; } numElements++; }
list
head tail numElements=2 c
Cost? O(1)
10
addFirst(<E> value)
public void addFirst(E value) { head = new Node<E> (value, head); if (tail == null) { tail = head; } numElements++; }
Cost? tail
60
-3
tail
60
-3
11
head
-3
tail
60
-3
12
Interface java.util.List
Array-like operations: public void set (int index, Object o) public Object get (int index) addFirst and public int size() addAfter arent part
of the List interface! Insertion and removal: What should we do? public boolean add (Object o) public void add (int index, Object o) public Object remove (int index) public boolean remove (Object o)
Other useful operations: public boolean contains (Object o) public int indexOf (Object o)
13
14