My dipslay function of linked list is as follows:-
public void display()
{
cur = first;
if(isEmpty())
{
System.out.println("no elements in the list");
}
else
{
System.out.println("elements in the list are:");
do {
System.out.println(first.data);
first = first.link;
} while(first.link!=null);
first=cur;
}
where curr and first are references of class node
public class node
{
int data;
Node link=null;
}
why is this function only printing the last element?
The function looks more or less correct. However why are you setting
curtofirstand then usingfirstto do the iteration? Just usecurin the iteration so you don’t have to resetfirst.Check to make sure you’re adding nodes into the list correctly. So if you think there are 3 elements in the list, run this in
display():This is to check if your links are correct.