I am learning about linked lists, and so far find them to be very confusing. Take for example my delete method, which seems to be able to delete an object at the head of the list, but doesn't do anything if it exists anywhere else in the list. Here's my linked list class (the myNode class simply holds both the object data and myNode recurrence variables, it does nothing else):
public class linkedList implements myLinkedList { public myNode head; public myNode temp = new myNode(); public myNode previous = new myNode(); public linkedList() { head = new myNode(); head = null; } public void insert(Object x) { if(lookup(x) == false) { myNode insert = new myNode(); insert.data = x; insert.next = head; //place insert in front of head head = insert; //points head to beginning of list } } public void delete(Object x) { previous = null; temp = head; while(temp != null) { if(temp.data.equals(x)) { if(previous == null) //item removed is first on the list { head = head.next; return; } else { previous.next = temp.next; return; } } else { previous = temp; temp = temp.next; } } return; } public boolean lookup(Object x) //interface in lab says public Object, but directions specify for it to return boolean value { temp = head; while(temp != null) { if(temp.data.equals(x)) return true; temp = temp.next; } return false; } public boolean isEmpty() { if(head==null) return true; else return false; } public void printList() { temp = head; while(temp != null) { System.out.println(temp.data.toString()); temp = temp.next; } } }
If temp points to head at the start of the method, and every time temp crawls though the list previous is declared as the previous temp, then why doesn't previous.next = temp.next effectively take temp out of the list?