Last active
October 2, 2018 03:41
-
-
Save sahands/9221612 to your computer and use it in GitHub Desktop.
Java - Singly-Connected Linked List Remove All Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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