【发布时间】: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