将第一个元素添加到队列中为空

时间:2014-01-03 00:11:16

标签: 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;
    }
}

当我向新队列添加一个元素并运行时,我列出了头部,尾部和列表:

Output:
Head=null Tail=null {}; 

{}表示列表不应该是空的,我做错了什么......

1 个答案:

答案 0 :(得分:3)

我认为你在队列中插入的逻辑是错误的......

请查看队列here

的算法和实现

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

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

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

    tail = n;
}