微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有链表的 C++ 队列

如何解决带有链表的 C++ 队列

问题:

struct QueueNode {
    int data;
    QueueNode *next;
};

  • int size() const:返回数据大小。
  • bool is_empty() 常量:
  • void enqueue(int val):在列表末尾添加一个新节点。
  • void dequeue():删除head指向的节点。
  • int top() const:返回接下来要出队的数据。

这是我的代码

class Queue {
    private:
        QueueNode *_head = NULL,*_tail = NULL;
        int _size = 0;
    public:
        int size() const {
            if (! is_empty())
              return _size;
        }
        bool is_empty() const {
            if (_size == 0)
                return true;
            else
                return false;
        }
        void enqueue(int val) {
            QueueNode *n = new QueueNode;
            n -> data = val;
            n -> next = NULL;
            if (is_empty()) {
                _head = n;
                _tail = n;
                _size ++;
            }
            else {
                _tail -> next = n;
                _tail = n;
                _size ++;
            }
        }
        void dequeue() {
            QueueNode *temp;
            temp = _head;
            if (! is_empty()) {
                _head = _head -> next;
                delete temp;
                _size --;
            }
        }
        int top() const {
            if (! is_empty())
                return _head -> data;
        }
};

在线裁判显示错误答案。 我认为“int top() const”是错误的。 但我不知道。 请求帮忙。 谢谢。

解决方法

正如@Kaylum 所指出的,如果队列为空,您还没有返回队列的大小。在这种情况下,它应该返回 0,但您的 size() 方法中没有其他部分。

这应该可行:

int size() const {
            if (! is_empty())
              return _size;
            else
              return 0;
        }

编辑:同样,你也应该从 top() 返回一些东西。如果您使用的是在线法官,那么它会指定在空队列的情况下返回的内容。请再次阅读约束条件,我想这会有所帮助。它很可能是一些异常或一些默认整数,在线法官判断空队列的输出时需要这些。

,

我的回答。谢谢大家。

class Queue {
    private:
        QueueNode *_head = NULL,*_tail = NULL;
        int _size = 0;
    public:
        int size() const {
            if (! is_empty())
              return _size;
            else
              return 0;
        }
        bool is_empty() const {
            if (_size == 0)
                return true;
            else
                return false;
        }
        void enqueue(int val) {
            QueueNode *n = new QueueNode;
            n -> data = val;
            n -> next = NULL;
            if (is_empty()) {
                _head = _tail = n;
                _size ++;
            }
            else {
                _tail -> next = n;
                _tail = n;
                _size ++;
            }
        }
        void dequeue() {
            QueueNode *temp;
            temp = _head;
            if (! is_empty()) {
                _head = _head -> next;
                delete temp;
                _size --;
            }
        }
        int top() const {
            if (! is_empty())
                return _head -> data;
        }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。