Java 获取作为Null添加到队列的第一个元素

Java 获取作为Null添加到队列的第一个元素,java,c++,queue,Java,C++,Queue,嘿,伙计们,这是我的代码: public void add(int data) { Node n = new Node(data); if (n.next == null) { head = tail = n; } else { tail.next = n; n.next = null; n = tail; } } 当我向新队列中添加一个元素并运行时,我列出了头、尾和列表: O

嘿,伙计们,这是我的代码:

public void add(int data) {
Node n = new Node(data);         
    if (n.next == null) {
        head = tail = n; 
    } 
    else {
        tail.next = n;
        n.next = null;
        n = tail;
    }
}
当我向新队列中添加一个元素并运行时,我列出了头、尾和列表:

Output:
Head=null Tail=null {}; 

{}表示列表在不应该为空时为空,我做错了什么…

我认为您插入队列的逻辑是错误的

请看一下队列的算法和实现

对于您的示例,请尝试更新以下内容:

public void add(int data) {
    Node n = new Node(data); 
    n.next = null;

    if (head == NULL) {
        head = n;
    } else {
        tail->next = n;
    }

    tail = n;
}

您应该标记这个C或C++(无论您使用的是什么),这样就可以看到更多的视图。我在发布时对站点是新的,谢谢,我如何更新标签字段,不受欢迎,您应该能够点击“编辑”,在您的帖子下面,上面的注释:-如果应该是:如果(头=空)谢谢RakHi。