I am new to C++ and only know Java.
I am trying to create a singly linked list in C++ that will allow me to store integer numbers within the nodes. I want also to have the IntNode
class and IntLinkedList
class in separate files from the main file.
However, it's not working, I think it has something to do with my add()
method for my IntLinkedList
class.
This is the main.cpp
file:
#include <iostream>
#include "IntNode.hpp"
#include "IntLinkedList.hpp"
int main(int argc, const char * argv[])
{
//Initializing Variables
IntLinkedList myList;
myList.add(5);
std::cout << "-------Done.------";
return 0;
}
This is the IntNode.cpp
file:
#include <stdio.h>
#include "IntNode.hpp"
IntNode::IntNode(int newData, IntNode *newLink)
{
data = newData;
link = newLink;
}
int IntNode::getData()
{
return data;
}
IntNode IntNode::getLink()
{
return *link;
}
void IntNode::setData(int newData)
{
data = newData;
}
void IntNode::setLink(IntNode *newLink)
{
link = newLink;
}
This is the IntNode.hpp
header file:
#ifndef IntNode_h
#define IntNode_h
class IntNode
{
private:
int data;
IntNode *link;
public:
IntNode(int newData, IntNode *newLink);
int getData();
IntNode getLink();
void setData(int newData);
void setLink(IntNode *newLink);
};
#endif /* IntNode_h */
This is the IntLinkedList.cpp
file:
#include<iostream>
#include "IntLinkedList.hpp"
#include "IntNode.hpp"
IntLinkedList::IntLinkedList()
{
head = nullptr;
tail = nullptr;
numElements = 0;
}
void IntLinkedList::add(int newElement)
{
if(!(tail))
{
*head = IntNode(newElement, nullptr);
tail = head;
}
else
{
*tail = IntNode(newElement, nullptr);
tail->getLink() = *tail;
}
numElements++;
}
This is the IntLinkedList.hpp
header file:
#ifndef IntLinkedList_hpp
#define IntLinkedList_hpp
#include <stdio.h>
#include "IntNode.hpp"
class IntLinkedList
{
private:
IntNode *head;
IntNode *tail;
int numElements;
public:
IntLinkedList();
void add(int newElement);
};
#endif /* IntLinkedList_hpp */
When I run the code, it gave me this:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
and highlights this piece of code, which is part of the IntLinkedList::add()
method:
*head = IntNode(newElement, nullptr);