简体   繁体   中英

Why my display function of linked list always printing the last element?

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 cur to first and then using first to do the iteration? Just use cur in the iteration so you don't have to reset first .

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() :

System.out.println(first.data);
System.out.println(first.link.data);
System.out.println(first.link.link.data);

This is to check if your links are correct.

It is not possible to say for sure, but it is probable that your list actually contains only one element; ie that the code that creates the list is broken.

I should also point out that the display method should use a local variable to step through the elements. If you use an instance variable (eg first ) you are liable to get different methods interfering with each other.

Finally, your test for the end of the list is incorrect. Think carefully about what first and first.link point at when the while test is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM