: : : : public static int search(LinearNode L, Object target)
: : : : {
: : : : LinearNode temp = L;
: : : :
: : : : int index =0;
: : : : int found = -1;
: : : : while(found==-1 && index<size)
: : : : {
: : : :
: : : :
: : : :
if ((temp.getElement()).equals(target))
: : : :
: : : : found = index;
: : : : index++;
: : : :
L=(L.getNext()).getNext();
: : : :
: : : :
: : : : }
: : : : return found;
: : : : }
: : : :
: : : In your search() method you skip every other node, and you compare
: : : the target with only the first node. I've marked the wrong lines in
: : : red above.
: :
: :
: : Thanks I knew it was something to do with the search method because
: : everything else seems to work ok. Just can't get that bit right, any
: : ideas on how I can get it to search every other one instead of just
: : the first one?? Thanks x
: :
: :
: First you need to check which variable holds which value:
:
: - L is the first node
: - temp is the currect node
:
: In your code you are checking if temp equals the target. Then you
: move the L variable to the next's next node. Here's a simple example
: of how your code performs its search:
:
:
: 1 LinearNode temp = L;
: 2 while(found==-1 && index<size) {
: 3 if ((temp.getElement()).equals(target))
: 4 found = index;
: 5 L=(L.getNext()).getNext();
: 6 }
: :
: given this list: 1, 2, 3, 4, 5 and target = 2.
: Before line 1: L = 1
: Then after line 1: temp = 1
: In line 3 you compare temp to the target (i.e. 1.equals(2)) which is
: false.
: In line 5 you call L.getNext() (L = 2, inside brackets) and
: immediately call it again (L = 3, outside the brackets).
: Then back to line 2, and the loop continues.
: Again line 3 is executed: temp is compared to the target (i.e.
: 1.equals(2)) which is false.
: And then line 5 is executed again: L = 4 and L = 5.
: For the last time back to line 3.
: Still comparing temp to the target.
: Now inside the brackets in line 5 the next node is retrieved (L =
: null). And then getNext() is called again, but this time the object
: is null, throwing a NullPointerException.
: As you can see there are 2 mistakes in your code: line 3 and line 5.
: In line 3 you're checking the value of temp, but that variable
: always remains at the first node. In line 5 you're updating the
: variable L twice per iteration through the loop. This should only
: happen once.
Thanks, I understand what you mean. Going to have a go at it now, thanks x