【问题标题】:How to implement a Queue using Linked List in C++ by classes only如何仅通过类在 C++ 中使用链表实现队列
【发布时间】:2021-04-24 15:01:38
【问题描述】:

我有一个链表类,像这样实现(也经过测试):

template <class T>
class LList {
    LNode<T>* head;
    LNode<T>* tail;
    int size; // proporciona muitas vantagens
    LNode<T>* rCopy(LNode<T>* right);
public:
    LList() : head(nullptr), tail(nullptr), size(0) {}
    LList(const LList& other) :
            head(nullptr), tail(nullptr), size(0) {
        *this = other;
    }
    ~LList() { clear(); }

...
    // O(1)
    void insertAtBack(T newvalue) {
        LNode<T>* tmp = new LNode<T>(newvalue, nullptr);
        tail->next = tmp;
        tail = tmp;
        if (head == nullptr)
            head = tmp;
        this->size++;
    }
...
};

然后,我创建了一个 Queue 类:

template <class T>
class Queue {
private:
    LList<T> lista;
public:
//    Queue() : lista() {} ??? don't know how to do it
    void enqueue(T element);
    T peek();
    void dequeue();
    int size();
    bool isEmpty();
    void sizeLog();
};

template<class T>
void Queue<T>::enqueue(T element) {
    lista.insertAtBack(element);
}

但我不能在 main 上使用它,任何入队尝试都会导致 for 循环崩溃,返回错误代码 -1073741819。函数isEmpty() 工作并显示true

Queue<int> f;
std::cout << "created" << endl;
std::cout << f.isEmpty() << endl;

for (int i=0; i<10; i++) {
    f.enqueue(i*5);
}

输出:

created
1

Process finished with exit code -1073741819 (0xC0000005)

我尝试为 Queue 类编写一个构造函数来初始化 LList 类,但找不到正确的方法。如果我写一个 main 函数只测试 LList 类,我就不需要初始化,因为它的构造器已经在工作了。

【问题讨论】:

  • 可以添加Queue::enqueue的函数定义吗?

标签: c++ queue singly-linked-list


【解决方案1】:

最初tail, headnullptr,因此当插入第一个元素时,您会尝试在insertAtBack 中访问tail-&gt;next,其中tailnullptr,导致错误(可能是未捕获的异常),如果tailnullptr,只需为其分配 tmp 值。放置 nullptr 检查表达式,如下所示..


// O(1)
    void insertAtBack(T newvalue) {
        LNode<T>* tmp = new LNode<T>(newvalue, nullptr);

        // if it is nullptr, 
        // it is the first and only element
        // so head = tail = tmp
        if(tail != nullptr) 
            tail->next = tmp;
        tail = tmp;
        if (head == nullptr)
            head = tmp;
        this->size++;
    }

``

【讨论】:

  • 我错过了一个简单的测试:if (tail != nullptr),对不起,我专注于构造函数。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
相关资源
最近更新 更多