简体   繁体   中英

Null Pointer exception while using Linked List in c++

I have an error of " read access violation " or as well " Segmentation fault ".

Here is my Code:

#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";

}

The error is in Insert Function in the LinkedList class.

In actual an exception pops up in this function at line number 52 .

I am using VISUAL STUDIO 2019 as my IDE. I shall be very thankful if anyone helps me to resolve it. I have looked about this error it was about my temp->next is Null but now I do not know how catch this flaw as in initial state I have inititalised the Next with Head but beside of this it is still giving the same error.

When you insert into the last position, handle it as the same way you did in push_back() .

Edit: I didn't notice that you modified the head pointer in your print function..that is the root cause, as pointed out by @retired-ninja

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM