Lec7A_LinkedList
Lec7A_LinkedList
a b c d e
c a e d b
firstNode
null
a b c d e
null
a b c d e
null next
Node(Object element)
element
{this.data= element;} data
next null
data a b c d e
checkIndex(0);
return firstNode.data; // gets you to first node
OR
checkIndex(0);
desiredNode = firstNode;
return desiredNode.data;
firstNode
next null
data a b c d e
checkIndex(1);
desiredNode = firstNode.next; // gets you to second node
return desiredNode.data;
firstNode
null
a b c d e
checkIndex(2);
desiredNode = firstNode.next.next; // gets you to third
node
return desiredNode.data;
firstNode
null
a b c d e
null
a b c d e
desiredNode =
firstNode.next.next.next.next.next.next;
// gets the computer mad
// you get a NullPointerException
firstNode
null
a b c d e
remove(0)
firstNode = firstNode.next;
firstNode
null
c
a b c d e
beforeNode
first get to node just before node to be removed
beforeNode = firstNode.next;
firstNode
null
a b c d e
beforeNode
now change pointer in beforeNode
beforeNode.next = beforeNode.next.next;
firstNode
null
f a b c d e
newNode
Step 1: get a new node, set its data and link fields
Node newNode =
new Node(new Character(‘f’), firstNode);
firstNode
null
f a b c d e
newNode
firstNode = newNode;
firstNode
null
f a b c d e
newNode
null
a b c d e
beforeNode
• first find node whose index is 2
• next create a node and set its data and link fields
Node newNode = new Node(new Character(‘f’), beforeNode.next);
null
a b c d e
beforeNode
beforeNode = firstNode.next.next;
beforeNode.next = new Node(new Character(‘f’),
beforeNode.next);
A linked list is a dynamic data structure. The
number of nodes in a list is not fixed and can grow
and shrink on demand.
Any application which has to deal with an
unknown number of objects will need to use a
linked list.
One disadvantage against an array is that
it does not allow direct access to the individual elements.
If you want to access a particular item then you have to
start at the head and follow the references until you get to
that item.