繁体   English   中英

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

[英]Gettting First Element Added to a Queue as Null

嘿家伙这是我的代码:

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;
    }
}

当我向一个新的Queue添加一个元素并运行时,我列出了head,tail和list是什么:

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;
}

暂无
暂无

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

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