Lect 09
Lect 09
IntegerList
first
numElements 0
Adding a New Element
• Simple Case: add as first element
• Need to
– Create a new list node
– Link it into the list
public void add (int item)
// Place the new item into a list
{ ListNode node = new ListNode();
node.data = item;
node.next = first;
first = node;
numElements++;
} // add
public void add (int item) Adding 17
{ ListNode node = new ListNode();
node.data = item;
node.next = first;
first = node;
numElements++;
} // add
IntegerList
node
first
numElements 32
ListNode
data 3 -8 170
next
More Flexibility: Adding Nodes
at Any Position
• Need to work through the linked list to find
the correct position
Finding the Position
public void add (int item, int position)
{ if (position < 0)
throw new …Exception(…);
ListNode node = new ListNode();
node.data = item;
ListNode curr = first,
prev = null;
for (int k = 0;
k < position && curr != null;
k++)
// Find position
{ prev = curr;
curr = curr.next;
}
...
Finding the Position (cont.)
add(-4, 2)
IntegerList
first Position for
new node
numElements 4
ListNode
data -56 19 3 -2
next
prev curr
Linking in the New Node
...
node.next = curr;
if (prev != null)
prev.next = node;
else
first = node;
numElements++;
} // add