我正在玩一个链表,当我尝试打印出尾部的值和下一个值的地址时出现错误:
struct Node {
int n;
Node *next;
};
class LinkedList {
public:
Node *head = NULL;
Node *tail = NULL;
};
int main() {
LinkedList L;
L.head = NULL;
L.tail = NULL;
Node *new_node = new Node();
new_node->n = 1;
new_node->next = NULL;
L.tail->next = new_node;
L.tail = new_node;
cout << L.tail << endl;
cout << L.tail->next << endl;
}
考虑这些陈述:
L.tail = NULL;
//...
L.tail->next = new_node;
您正在尝试使用空指针访问内存。这调用了未定义的行为.
此外,这些作业:
LinkedList L;
L.head = NULL;
L.tail = NULL;
是多余的,因为类对其成员的默认初始化:
class LinkedList {
public:
Node *head = NULL;
Node *tail = NULL;
};