I can not seem to get my head around Linked Lists! For an assignment we have to insert numbers into a LinkedList in order. But my method seems to only insert one record! When I was just adding the new value to the end of the list all the values were added so it must be in this method. Basicly each new value gets set as the first Node, even if it shouldn't be.
Code:
public void insertNew(Object value){
ListNode next;
if(first == null){ //Check to see if there is atleast one Node already
next = new ListNode(value, null);
first = next;
last = first;
}
else{
ListNode temp = first; //Start at the beginning of the list.
ListNode back = null;
int myTemp = (Integer)temp.getValue();
int myNext = (Integer)value;
while(temp.getNext()!= null && myTemp < myNext){
System.out.println(myTemp + "<Temp Next>" + myNext);
back = temp;
myTemp = (Integer)temp.getValue();
temp = temp.getNext();
}
if(temp == null)
next = new ListNode(value, null);
else
next = new ListNode(value, temp.getNext());
if(back != null)
back.setNext(next);
}
}
I believe my basic algorithm is:
- Check to see if first Node is set.
- Loop through list comparing the value to the value I'm trying to insert.
- When the current value is greater then the value I'm inserting, but the new value infront of the current value. Make the value behind it(back) link to this new value, and the new value link to the current value.
Is this correct?