【问题标题】:Null Pointer exception while using Linked List in c++在 C++ 中使用链表时出现空指针异常
【发布时间】:2021-12-09 14:42:07
【问题描述】:

我遇到了“读取访问冲突”或“分段错误”的错误。

这是我的代码:

#include<iostream>

using namespace std;

class Node {
 int data;
 public:
Node* next;
Node(int d) :data(d), next(NULL) {}
int getData() {
    return data;
}
 };

class LinkedList {

Node* head;
Node* tail;

public:
LinkedList() :head(NULL), tail(NULL) {}

void push_front(int data) {
    if (head == NULL) {
        Node* n = new Node(data);
        head = tail = n;
    }
    else {
        Node* n = new Node(data);
        n->next = head;
        head = n;
     }
}

void push_back(int data) {
    if (head == NULL) {
        Node* n = new Node(data);
        tail = head = n;
    }
    else {
        Node* n = new Node(data);
        tail->next =n;
        tail = n;
    }
}

void insert(int data,int pos) {
    if (pos == 0) push_front(data);
    else {
        Node* temp = head;
        for (int i = 0; i < pos; i++) {
            temp = temp->next;
           
        }
        Node* n = new Node(data);
        n->next = temp->next;
        temp->next=n;
    }
}
void print() { 
    while (head != NULL) {
        cout <<  head->getData() << "=>";
        head = head->next;
    }
}
 };

int main() {
LinkedList l;
l.push_front(5);
l.push_back(8);
l.push_front(0);
l.print();
l.insert(9, 2);
cout << "\n";

}

错误出现在 LinkedList 类中的插入函数中。

实际上一个exception在这个函数中弹出第52行

我使用 VISUAL STUDIO 2019 作为我的 IDE。 如果有人帮助我解决它,我将非常感激。 我已经查看了这个错误,它是关于我的 temp->next is Null 但现在我不知道如何捕获这个缺陷,因为在初始状态我已经用 Head 初始化了 Next 但除此之外它仍然给出相同的错误。

【问题讨论】:

  • 崩溃在insert函数中。 tempNULL 这里:temp = temp-&gt;next;
  • 是的,我知道,但如何解决它告诉我这个
  • print 在此处修改headhead = head-&gt;next; 所以head 在完成后指向列表末尾。使用不同的变量来迭代列表。如果 print 是一个 const 函数,编译器将拒绝不正确的代码。
  • 得到它错误已解决非常感谢你

标签: c++ linked-list nodes singly-linked-list


【解决方案1】:

当你插入到最后一个位置时,像在 push_back() 中一样处理它。

编辑:我没有注意到您修改了打印函数中的头指针。这是根本原因,正如@retired-ninja 指出的那样

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多