开发者

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

开发者 https://www.devze.com 2023-03-23 11:31 出处:网络
My dipslay function of linked list is as follows:- public void display() { cur = first; if(isEmpty()) { System.out.println(\"no elements开发者_开发问答 in the list\");

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; i.e. 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 (e.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消