PDA

View Full Version : LinkedLists (Java)

squirellplaying
04-10-2005, 03:13 AM
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.

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?

squirellplaying
04-12-2005, 02:26 AM
I've edited it too :

public void insertNew(Object value)
{
ListNode temp, back, next;
int difference;

if(first == null || ((Integer)first.getValue() - (Integer)value) <= 0) //check the first value
{
}
else if( ((Integer)getLast() - (Integer)value) > 0 && getLast()!=null){ //check the last value
}
else { //put inbetween somewhere
temp = back = first;

while(((Integer)temp.getValue() - (Integer)value) >= 0 && getLast()!=null){
back = temp;
temp = temp.getNext();
}
next = new ListNode(value, temp);
back.setNext(next);
}

}

Now I get stuff about the addLast method. It should accept an object, which it does, so I don't understand.