首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >队列实现不返回第一个元素

队列实现不返回第一个元素
EN

Stack Overflow用户
提问于 2019-05-27 04:35:53
回答 1查看 189关注 0票数 2

我想用Java中的链表来模拟一个队列。我的一般模式是有一个节点列表,其中有两个节点指向队列的第一个和最后一个元素。当我执行dequeue()时,我想要获得第一个元素。到目前为止,我所做的工作如下:

代码语言:javascript
运行
复制
public class Node {
    public Object e;
    Node next;

    public Node(Object e) {
        this.e = e;
    }
}

public class Queue {
    Node queueList;
    Node first, last;
    int count;

    public void enQueue(Object n) {
        Node temp = new Node(n);
        temp.next = last;
        last = temp;
        if (queueList == null) {
            first = temp;
        }
        count++;
        queueList=temp;
    }

    public Object deQueue() {
        Node previous = last;
        Node current = last.next;
        Object num = null;
        if (count == 0)
            System.out.println("empty queue");
        else {
            while (current.next != null) {
                previous = previous.next;
                current = current.next;
            }
            num = first.e;
            first = previous;
            count--;
        }
        return num;
    }

    public void print() {
        Node current = last;
        while (current != null) {
            System.out.println(current.e);
            current = current.next;
        }
    }
}

我不想使用双向链表,所以对于dequeue()操作,我要做的就是用两个指针遍历我的列表,如下所示:

因此,当current.next指向空值时,我希望前一个节点是第一个节点。我得到的问题是,当我打印队列的元素时,它仍然打印我: 10,15,5, 18,但是18值没有被删除。有什么帮助吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-27 04:57:37

基本上,我会在你的代码中纠正两件事。首先,没有为Queue字段赋值,我也怀疑它的实用性,基本上可以使用first来应用它的逻辑

代码语言:javascript
运行
复制
public void enQueue(Object n) {
    Node temp = new Node(n);
    temp.next = last;
    last = temp;
    if (first == null) { <--- HERE
        first = temp;
    }
    count++;
}

第二个问题是,您永远不会将队列的新头部的值放在null旁边,这在这种情况下是需要的

代码语言:javascript
运行
复制
public Object deQueue() {
    Node previous = last;
    Node current = last.next;
    Object num = null;
    if (count == 0) System.out.println("empty queue");
    else {
        while (current.next != null) {
            previous = previous.next;
            current = current.next;
        }
        num = first.e;
        first = previous;
        first.next = null; <--- HERE
        count--;
    }
    return num;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56317169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档