> public Object getItemAtPosition(int position) {
> if (position<0 || position >= this.length){
[quoted text clipped - 6 lines]
> return curr.getData();
> }
If that code is correct (it looks OK to me) then you also understand how to
find the /Node/ at a given position. Exactly the same code as above, but you
return the Node instead of the data it contains.
But I think you may have confused yourself by calling the variable "curr"
(presumably short for "current"). That variable is local to the method, and
when the method returns the variable vanishes. So calling getItemAtPosition()
doesn't "advance" anything -- it just finds the data in the list and returns
it.
> public boolean insert (Object data,int position){
> if (position<0 || position > this.length ){
[quoted text clipped - 7 lines]
> this method.
> getItemAtPosition(position);
If you write another method like getItemAtPosition(), but which returns the
Node instead of the data it contains, then you could use that here. Say you
call it getNodeAtPosition(). You call that, and it returns a reference to the
Node you want. Since you want to do something to that node, you'll have to
assign the reference to a local variable; something like:
Node previous = this.getNodeAtPosition(position);
Now you can add your new node after it. You won't be able to use temp.next and
previous.next fields directly, but you can use your getNext() and setNext()
methods to do just the same thing.
Node temp = new Node(data);
temp.setNext(previous.getNext());
previous.setNext(temp);
Actually my code is wrong -- it will always insert the item /after/ the
numbered position. E.g. if you asked to insert an item at position 0, it would
put it after the existing item at that position (so it would end up at position
1). You'll have to make small changes to fix that up, but it's not related to
your problem here, and anyway I think you can do that easily (but expect to
have to handle position 0 specially).
Oh, by the way:
> public Node(Object data){
> this.data = null;
> }
You have a typo there -- you should be assigning
this.data = data;
-- chris
Taria - 21 Feb 2007 22:12 GMT
On Feb 21, 12:35 am, "Chris Uppal" <chris.up...@metagnostic.REMOVE-
THIS.org> wrote:
> > public Object getItemAtPosition(int position) {
> > if (position<0 || position >= this.length){
[quoted text clipped - 62 lines]
>
> -- chris
Great! Thank you Chris, I'm stuck in school for a long time today and
can't work on this code for another 7 hours but I'll be trying it
again after that. Thank you very much for your help.