Lec7B LinkedList
Lec7B LinkedList
Node representation
class Node
{
// data members
Object data; // data field
next
Node next; // link field
data
null next
Node(Object element)
element
{this.data= element;} data
null
a b c d e
Use Node
next (datatype Node)
public LinkedList()
{ firstNode=null;
size=0;
}
The Method isEmpty
null
a b c d e
null
a b c d e
firstNode = firstNode.next;
Remove An Element
public Object remove(int index)
{
checkIndex(index);
Object removedElement;
null
a b c d e
beforeNode
removedElement = q.next.data;
q.next = q.next.next; // remove desired node
}
size--;
return removedElement;
}
One-Step add(0,’f’)
firstNode
null
f a b c d e
newNode
if (index == 0)
// insert at front
firstNode = new Node(theElement, firstNode);
else ……?
}
Two-Step add(3,’f’)
firstNode newNode
f
null
a b c d e
beforeNode
// insert after p
p.next = new Node(theElement, p.next);
}
size++;
}
Linked Lists
Advantages
Quick insertion –O(1)
Dynamic size
Disadvantages
Slow search - O(n)
Slow deletion - O(n)
Advantages Disadvantages
Unordered array list Insertion - O(1) Search – O(n)
Deletion – O(n)
Fixed array size
Ordered array list search –O(log2 n) Insertion - O(n)
Deletion - O(n)
Fixed array size
Linked list Insertion - O(1) Search – O(n)
Dynamic size Deletion – O(n)
Linked List With Header Node
headerNode
null
a b c d e
Now add/remove at left end (i.e., index = 0) are no different from any
other add/remove. So add/remove code is simplified.
Empty Linked List With Header Node
headerNode
null
Circular List
firstNode
a b c d e
Useful, for example, when each node represents a supplier and you want each
supplier to be called on in round-robin order.
a b c d e
It is often useful to have a last node pointer rather than a first node
pointer. By doing this, additions to the front and end become O(1).
Empty Doubly Linked Circular List With Header Node
headerNode
java.util.LinkedList