Skip to content

Instantly share code, notes, and snippets.

@danlamanna
Created February 19, 2012 20:29
Show Gist options
  • Save danlamanna/1865613 to your computer and use it in GitHub Desktop.
Save danlamanna/1865613 to your computer and use it in GitHub Desktop.
Removing a specific node from a linked list.
protected void _removeNodeFromLinkedList(Node toBeRemoved) {
Node previousNode = null;
Node nextNode = this.pFirst.pNext;
for (Node currentNode = this.pFirst; currentNode != null; currentNode = currentNode.pNext) {
if (currentNode == toBeRemoved) {
// We need to remove the first from the linked list
if (currentNode == this.pFirst) {
// Set the next node (second) to be pFirst
this.pFirst = nextNode;
} else if (currentNode == this.pLast) { // We need to remove the last node from the linked list
// The previous node is now the last, so it has no pNext
previousNode.pNext = null;
// Set this objects pLast to the previous node
this.pLast = previousNode;
} else { // All other nodes follow the same rules for removal
// This tells the previous node that it's next node is the one in front of our current,
// skipping this node altogether.
previousNode.pNext = nextNode;
}
// "Unset" the node in memory for GC
currentNode = null;
return;
}
previousNode = currentNode;
nextNode = currentNode.pNext.pNext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment