提问者:小点点

用类实现C++中的链表队列


我有一个链表类,这样实现(也进行了测试):

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类,我就不需要初始化了,因为它的构造器已经在继续这个工作了。


共1个答案

匿名用户

最初,tail、headnullptr所以当插入第一个元素时,您尝试访问insertatback中的tail->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++;
    }

``

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(类|c++|中|链表|队列)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?