hello, below is a code i wrote for finding a node in a linked list, and deleting it
// Locate the node containing the data object that matches (use the // equals method from CityLocation) aCity, and remove it from the list. // Return a link to the data object contained in the deleted node. // Return null if the node can not be located. // The complexity is O(n) public CityLocation delete (CityLocation aCity) { if (!isEmpty()) { // checks for empty list
// if list is not empty, create 2 variables to traverse list // one holds the current element, and the other the previous one // assumes direction is from head to tail CityLocationDLNode nextNode = this.head.next; CityLocationDLNode currNode = this.head;
// if only one node in list if (nextNode == null) { this.head = null; }
// traverse list in search of target node while (nextNode != null) { // checks if data element of node is target value if (location.info.equals (aCity)) { // if found, delete element by skipping over next node currNode = nextNode; } // end if } // end while } // end outer if return location.info;
Why don't you take a look at the java.util.LinkedList API. All you need to do is iterate through the list performaing a cast on the object as you pull them out, they need to be cast and then compared, you should implment the equals method on your objects. This way its easy to compare.