Skip to content

Instantly share code, notes, and snippets.

@sahands
Last active October 2, 2018 03:41
Show Gist options
  • Save sahands/9221612 to your computer and use it in GitHub Desktop.
Save sahands/9221612 to your computer and use it in GitHub Desktop.
Java - Singly-Connected Linked List Remove All Method
/*
* PURPOSE:
* Remove all instances of value from the list.
*
* PRECONDITIONS:
* None.
*
* Examples:
* If l is {67,12,13,12} then after l.remove(12), l is {67,13}
* If l is {1,2,3} then after l.remove(2), l is {1,3}
* If l is {1,2,3} then after l.remove(99), l is {1,2,3}
*/
public void remove (T value)
{
Node<T> prev = null;
Node<T> cur = head;
while(cur != null) {
if(cur.item.equals(value)) {
// Found something to remove
count--;
if(prev == null) {
head = cur.next;
} else {
prev.next = cur.next;
}
}
// Maintain loop invariant: prev is the node before cur.
if(cur.next != head) {
prev = cur;
}
cur = cur.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment