为什么我的链表程序在 Visual Studio Code 上出现“a.exe 已停止工作”错误?

问题描述 投票:0回答:1

我正在玩一个链表,当我尝试打印出尾部的值和下一个值的地址时出现错误:

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;
}
c++ linked-list singly-linked-list undefined-behavior null-pointer
1个回答
2
投票

考虑这些陈述:

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.