所以我试图创建一个链接列表类来更好地理解指针和数据结构是如何工作的,但我一直遇到 -11 SIGSEGV 错误。当我查看错误时,它说我可能正在使用取消引用的指针或访问超出其边界的数组,但这些对我的程序都没有意义。我到处寻找类似的问题,但似乎没有一个适用于我的程序。其他人可以看到我做错了什么吗?
#include <stdexcept>
#pragma once
using namespace std;
#define NODE typename LinkedList<T>::Node*
template <typename T>
class LinkedList {
public:
void AddHead(const T& data); //Adds new node to the beginning of the list
void AddTail(const T& data); //Adds new node to the end of the list
LinkedList(); //Default constructor
LinkedList(const LinkedList<T>& list); //Copy constructor
struct Node {
/*Individual node that stores the data*/
T data;
Node* prev;
Node* next;
Node(); //Default constructor for node
Node(T _data); //Data constructor for node
Node(T _data, Node* _prev, Node* _next); //Full constructor for node
};
private:
NODE head = nullptr;
NODE tail = nullptr;
unsigned int count;
};
/*Function definitions*/
template <typename T>
void LinkedList<T>::AddHead(const T& data) {
NODE tempRef = new Node(data, nullptr, head);
head->prev = tempRef;
head = tempRef;
delete tempRef;
count++;
}
template <typename T>
void LinkedList<T>::AddTail(const T& data) {
NODE tempRef = new Node(data, tail, nullptr);
tail->next = tempRef;
tail = tempRef;
delete tempRef;
count++;
}
template <typename T>
LinkedList<T>::LinkedList() {
count = 0;
head = nullptr;
tail = nullptr;
}
template <typename T>
LinkedList<T>::LinkedList(const LinkedList<T>& list) {
this->head = list.head;
this->tail = list.tail;
this->count = list.count;
}
/*Node Constructors*/
template <typename T>
LinkedList<T>::Node::Node() {
next = nullptr;
prev = nullptr;
}
template <typename T>
LinkedList<T>::Node::Node(T _data) {
next = nullptr;
prev = nullptr;
data = _data;
}
template <typename T>
LinkedList<T>::Node::Node(T _data, Node* _prev, Node* _next) {
next = _next;
prev = _prev;
data = _data;
}