简体   繁体   English

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

[英]Unable to display nodes of the list properly starting from the tail to head

My insert method explanation: I assigned the "next variable" of tail to hold the address of the old node. 我的插入方法说明:我分配了tail的“下一个变量”来保存旧节点的地址。 I assigned the tail with the new node inserted into the list. 我分配了带有新节点插入列表的尾部。

I tried to display the list starting from the tail and going through the list until it reached the head. 我试图从尾部开始显示列表,直到列表到达头部为止。

Problem: But the input displayed C which is not what I wanted. 问题:但是输入显示C,这不是我想要的。 Display method is supposed to display C, B, A. 显示方法应该显示C,B,A。

I even debug my code on paper. 我什至在纸上调试我的代码。 I don't know why the display is not retrieving the last address of the nodes linked in the linked list. 我不知道为什么显示内容没有检索链接列表中链接的节点的最后一个地址。 It only retrieved the last node in the list and display only that last node in the list. 它仅检索列表中的最后一个节点,并仅显示列表中的最后一个节点。

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;

        }

    }

You have created a singly linked list. 您已创建一个单链列表。 The list has a head and tail, the links are from head to tail. 列表有头和尾,链接从头到尾。 A singly linked list by design has one direction "forward". 设计上的单链接列表具有一个“前进”方向。 With elements [a,b,c] the list is linked a->b->c. 使用元素[a,b,c],列表链接为a-> b-> c。 To print the elements in reverse order you have at least two options. 要以相反的顺序打印元素,您至少有两个选择。 Use recursion to print the elements c , b, a or implement a doubly linked list 使用递归来打印元素c,b或a或实现一个双向链表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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