插入LinkedList尾部时出错

时间:2015-12-20 02:03:55

标签: java linked-list

尝试在单链表的末尾插入,但是我在输出中发现了一些错误。这是我的代码:

    public class LinkRemove
{
    private static final int N = 5;
    public static void main(String[] args)
    {
        Scanner sx = new Scanner(System.in);
        Node first = new Node();
        Node tail = new Node();
        first=tail;

        for(int i=0;i<N;i++)
        {
            Node current = new Node();

            if(tail==null)
            {
                tail.data = sx.nextInt();
            }

            else
            {
                current.data = sx.nextInt();
                while(tail.link!=null)
                    tail = tail.link;
                tail.link = current;
            }


        }

        for(Node d = first;d.link!=null;d=d.link)
            System.out.println(d.data);


    }

    private static class Node
    {
        int  data;
        Node link;
    }
}

现在问题是,当我提供输入时:

2 4 6 8 10

我的输出为:

0 2 4 6 8

可能导致这种情况的原因是什么?为什么我在开始时会得到0? 请给出一个描述性的答案,谢谢!

3 个答案:

答案 0 :(得分:0)

第一个0来自节点(Node tail = new Node();)中字段的默认值。实际上,您希望将其设置为null而不是new Node()。同样适用于first。事实上,为什么不写信:

Node tail = null;
Node first = tail;

像迈克所说,你的终止条件不正确。

此外,

if(tail==null)
{
   tail.data = sx.nextInt();
}

根本没有意义。如果代码到达tail.data = ...,则它将是NullPointerException。你究竟想做什么?

答案 1 :(得分:0)

我稍微修改了你的代码

    public static void main(String[] args) {
    Scanner sx = new Scanner(System.in);
    Node first = null;
    Node tail = null;

    for (int i = 0; i < N; i++) {
        Node current = new Node();
        current.data = sx.nextInt();

        if(first == null) {
            first = current;
            tail = first;
        } else {
            tail.link = current;
            tail = current;
        }
    }

    for (Node d = first; d != null; d = d.link)
        System.out.println(d.data);

}

用于在节点中设置数据的逻辑不正确。首先,您必须设置第一个节点并设置tail = first 然后,将新节点添加到tail:tail.link = current。

希望这有帮助。

答案 2 :(得分:0)

试试这个

    Scanner sx = new Scanner(System.in);
    Node first = null;
    Node tail = null;

    for (int i = 0; i < N; i++)
    {
        Node current = new Node();
        current.data = sx.nextInt();

        if (tail == null)
        {
            first = tail = current;
        }
        else
        {
            tail = tail.link = current;
        }
    }
    for(Node d = first; d != null; d = d.link)
        System.out.println(d.data);
相关问题