链接列表插入(核心转储)

时间:2017-04-13 16:30:38

标签: c++ linked-list coredump

我的标题和投诉文件

*.html

我遇到此功能的问题

#ifndef VIKTOR_H_
#define VIKTOR_H_

#include <iostream>

template <class DataType>
class viktor {

private:
    template <class NodeType>
    struct Node {

        NodeType data;
        Node<NodeType> * next;

    };

    Node<DataType> * backPtr;
    int length;

public:

    viktor();
    ~viktor();

    DataType &operator [] (int) const;

    void push(const DataType &);

    friend std::ostream &operator << (std::ostream &strm, const 
viktor<DataType> &A){

        for(int i = 0; i < A.length; ++i) {

            strm << A[i] << " " << std::flush;
        }

        strm << std::endl;

        return strm;
    }
};
template <class DataType>
viktor<DataType>::viktor() {

backPtr = nullptr;

length = 0;
}
template <class DataType>
viktor<DataType>::~viktor() {

if ( length == 0 ) return;

Node<DataType>* previousPtr = backPtr;
Node<DataType>* nextPtr = backPtr->next;

while( nextPtr != backPtr )
{

    nextPtr = nextPtr->next;

    previousPtr->next = nullptr;
    delete previousPtr;
    length--;

}

backPtr->next = nullptr;
delete backPtr;
}
template <class DataType>
void viktor<DataType>::push(const DataType &item) {

Node<DataType>* newNode = new Node<DataType>;

newNode->data = item;

std::cout << "data: " << newNode->data << std::endl;

if(length != 0) {

    newNode->next = backPtr->next;
    backPtr->next = newNode;
}
else {

    newNode->next = newNode;
}

backPtr = newNode;

length += 1;
//std::cout << "Finished pushing..." << std::endl;
}
template <class DataType>
DataType &viktor<DataType>::operator [] (int i) const {

Node<DataType>* conductor = backPtr;

if (i > length) {

    throw "Item is inaccessible";
}
for (int j = 0; j <= i; ++j) {

        conductor = conductor->next;
}

return conductor->data;
}

#endif //VIKTOR_H_

我正在使用此测试驱动程序

template <class DataType>
void viktor<DataType>::push(const DataType &item) {

Node<DataType>* newNode = new Node<DataType>;

newNode->data = item;

std::cout << "data: " << newNode->data << std::endl;

if(length != 0) {

    newNode->next = backPtr->next;
    backPtr->next = newNode;
}
else {

    newNode->next = newNode;
}

backPtr = newNode;

length += 1;
//std::cout << "Finished pushing..." << std::endl;
}

现在它可以工作,如果我只推一次,但如果我做

int main() {

viktor<int> blah;

blah.push(2);

std::cout << blah << std::endl;
}

它运行并打印我想要的所有数据但是在程序结束时它会转储我的核心(如果你想要我可以提供特定的错误,但它只是一个内存映射,然后是blah.push(1); blah.push(2); )< / p>

1 个答案:

答案 0 :(得分:0)

我修好了!谢谢一些程序员老兄!所以问题是我的解构函数,我所做的是将data() { let self = this; return { .... const start = self.$options.methods.createDate(-7); } } 更改为previousPtr->next = nullptr;