1.
Why
public static int count=0;
?
That means there is a single
count
for every instance, remove the
static
!
2.
Change the access for the member variables to
private
.
3.
Change method
linknext
to
setNextLink
, this is a convention in Java that works well.
4.
insertFirst
must use the method
setNextLink
, as the member varianble cannot be accessed:
public void insertFirst(String str) {
Link next = new Link(str);
count++;
next.setNextLink(first);
first=next;
}
5.
insertN will not work as planned. Allow the Link class to do the work for you :
class Link
Link getLink (int position) {
if (position <= 0 || this.nextlink == null) {
return this.nextLink;
}
else
{
return this.nextlink.getLink(position - 1);
}
}
}
Then to add after a position:
public void insertAfter(int pos,String str){
Link previous = this.first.getLink(pos);
if (previous != null) {
Link next = previous.getNextLink();
Link insert = new Link(str);
previous.setNextLink(insert);
insert.setNextLink(next);
}
}
Simple and less code to go wrong.