我有一个链表类,这样实现(也进行了测试):
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++;
}
...
};
然后,我创建了一个队列类:
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)
我尝试为队列类编写一个构造函数来初始化LList类,但找不到正确的方法。如果我编写一个main函数只测试LList类,我就不需要初始化了,因为它的构造器已经在继续这个工作了。
最初,tail、head
是nullptr
所以当插入第一个元素时,您尝试访问insertatback
中的tail->next
,其中tail
是nullptr
导致错误(可能是未捕获的异常),如果tail
是nullptr
,只需给它分配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++;
}
``