Linkedlist in Java
Linkedlist in Java
Lecture Notes
Linked List Implementation
Weiss Ch. 6, pp. 183-205
Weiss Ch. 17, pp. 537-548
1
Collections
examples:
java.util.ArrayList, java.util.HashMap,
java.util.TreeSet
Java's Collection
interface
Java provides an interface java.util.Collection
to represent many kinds of collections. It has the
following methods:
Collection
interface,cont'd.
public boolean isEmpty()
List features
Array list
10
ArrayList features
11
Collections class
public
public
public
public
public
public
public
public
static
static
static
static
static
static
static
static
Example:
Collections.sort(myArrayList);
12
Analysis of ArrayList
runtime
OPERATION
add to start of list
add to end of list
add at given index
clear
get
find index of an object
remove first element
remove last element
remove at given index
set
size
toString
RUNTIME (Big-Oh)
O(n)
O(1)
O(n)
O(1)
O(1)
O(n)
O(n)
O(1)
O(n)
O(1)
O(1)
O(n)
13
Open questions
16
17
Node implementation
/* Stores one element of a linked list. */
public class Node {
public Object element;
public Node next;
public Node(Object element) {
this(element, null);
}
1.
before:
after:
19
after:
3.
before:
after:
20
after:
5.
before:
after:
21
after:
7.
before:
after:
22
Linked list
23
empty list
(myFront == null)
an add operation
a remove operation
a get operation
a set operation
an index of (searching) operation
26
Analysis of LinkedList
runtime
OPERATION
add to start of list
add to end of list
add at given index
clear
get
find index of an object
remove first element
remove last element
remove at given index
set
size
toString
RUNTIME (Big-Oh)
O(1)
O(n)
O(n)
O(1)
O(n)
O(n)
O(1)
O(n)
O(n)
O(n)
O(n)
O(n)
27
An optimization: mySize
28
A variation: dummy
header
29
An optimization: myBack
Doubly-linked lists
32
Improved LinkedList
runtime
OPERATION
add to start of list
add to end of list
add at given index
clear
get
find index of an object
remove first element
remove last element
remove at given index
set
size
toString
RUNTIME (Big-Oh)
O(1)
O(1)
O(n)
O(1)
O(n)
O(n)
O(1)
O(1)
O(n)
O(n)
O(1)
O(n)
33
34
35
Iterators in Java
interface java.util.Iterator
Why?
What is the Big-Oh of get and set?
What is the Big-Oh of add and remove?
Does the array list iterator improve this?
37
38
(Why?)
39
40
41
Benefits of iterators
43
ListIterator interface
public
public
public
public
void add(Object o)
int nextIndex()
int previousIndex()
void set(Object o)
46
ListIterator usage
// print odd-valued elements, with their indexes
for (ListIterator itr = list.listIterator();
itr.hasNext(); ) {
int element = ((Integer)itr.next()).intValue();
if (element % 2 == 1)
System.out.println(itr.previousIndex() + ": " +
element);
}
// add a 0 after any odd element
for (ListIterator itr = list.listIterator();
itr.hasNext(); ) {
int element = ((Integer)itr.next()).intValue();
if (element % 2 == 1)
itr.add(0);
}
47
ListIterator benefits
48
Summary