In my C++ project, all classes use linked list class, and when I run the project, it throws a nullptr
exception:
I tried to solve the problem with Copilot AI, but it didn’t solve my problem, it provided the debugging throw
statements.
The code of my linked list class:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Services.h"
#include "Employee.h"
#include "transaction.h"
#include "Citizen.h"
#include <iostream>
using namespace std;
template <typename T>
class Node {
public:
T data;
Node* next;
Node* prev;
Node(T val) : data(val), next(nullptr), prev(nullptr) {}
};
template <typename T>
class LinkedList {
private:
Node<T>* head;
Node<T>* tail;
public:
LinkedList() : head(nullptr), tail(nullptr) {}
Node<T>* getHead() { return head; }
Node<T>* getTail() { return tail; }
void addHead(T val) {
Node<T>* newNode = new Node<T>(val);
if (newNode == nullptr) {
throw std::runtime_error("Memory allocation failed for newNode.");
}
if (head == nullptr) {
head = tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
// Debugging statements to ensure head and tail are not nullptr
if (head == nullptr || tail == nullptr) {
throw std::runtime_error("Head or Tail is nullptr after adding a new head.");
}
if (head->next != nullptr && head->next->prev != head) {
throw std::runtime_error("Incorrect previous pointer assignment in the linked list.");
}
}
};
#endif // LINKEDLIST_H
I used this linked list to implement queue from citizen node and stack from transaction node so my whole project depend on it
MHD Kh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
11