Deletion by Key
- We traverse through the linked list looking for the key
- We maintain a pointer to the node previous to the match
- If the head is a match we simply reset the head pointer
- If another node is a match, we set its previous node to point to the node after the match node
public void remove(Type item) {
Node previous = null;
Node current = head;
if (head.data.equals(item)) {
head = head.next;
return;
}
while (current != null && !current.data.equals(item)) {
previous = current;
current = current.next;
}
if (current == null)
return;
previous.next = current.next;
}
Deletion by Node
Here we match by node and not by key.
public void remove(Node refNode)
{
Node previous = null;
Node current = head;
if (head.equals(refNode)) {
head = head.next;
return;
}
while (current != null && !current.equals(refNode)) {
previous = current;
current = current.next;
}
if (current == null)
return;
previous.next = current.next;
}
No comments:
Post a Comment