无法正确显示从尾部到头部的列表节点



我的插入方法说明:我分配了尾巴的"下一个变量"来保存旧节点的地址。我分配了尾部,并将新节点插入到列表中。

我试图显示列表,从尾部开始,穿过列表,直到它到达头部。

问题:但是输入显示的 C 不是我想要的。显示方法应该显示C,B,A。

我什至在纸上调试我的代码。我不知道为什么显示没有检索链表中链接的节点的最后一个地址。它仅检索列表中的最后一个节点,并仅显示列表中的最后一个节点。

public static void main(String[] args)
    {
        LinkedList list = new LinkedList();
        list.insert("A");
        list.insert("B");
        list.insert("C");
        list.display();
    }
public void insert(String data)
    {
        Link link = new Link(data);
        // this code only executes the first time when the list has 
        // no node
        if(head == null)
        {
            head = link;
            tail= link;
        }
        // this code will execute when the linked list has one or more node                                 
        else
        {
            tail.next = tail;
            tail = link;
        }
    }
    public void display()
    {
        while(tail != null)
        {
            System.out.println(tail.data);
            tail = tail.next;
        }
    }

您已经创建了一个单向链表。列表有头和尾,链接是从头到尾的。单链表的设计有一个方向"向前"。与元素 [a,b,c] 链接的列表为 a->b->c。要以相反的顺序打印元素,您至少有两个选项。使用递归打印元素 c、b、a 或实现双向链表

最新更新