I am writing node and I"ve met a problem this is recognized as nullptr by if while it shouldn't be (At least that's what I think). And there is another problem when I use constructor with value this->next points to this.
I expect explenation or if I understend something wrong solution to my problem. I really don't know why this happens. Maybe I'm not understanding how this is working exacly.
#pragma once
#include"mstring.h"
template<typename T>
class node
{
private:
T data;
node* next;
node* prev;
public:
node();
node(T _data);
~node();
T& operator[](int index);
int GetSize();
void AddFront(T new_data);
void AddBack(T new_data);
void DeleteFront();
void DeleteBack();
};
template<typename T>
node<T>::node() : prev(nullptr), next(nullptr) {};
template<typename T>
node<T>::node(T _data)
{
data = _data;
prev = nullptr;
next = nullptr;
}
template<typename T>
void node<T>::AddFront(T new_data)
{
node* temp_node = new node();
temp_node->prev = nullptr;
temp_node->data = new_data;
temp_node->next = this;
if (this != nullptr)
(this)->prev = temp_node;
*this = *temp_node;
}
template<typename T>
void node<T>::AddBack(T new_data)
{
node* temp_node = new node();
temp_node->next = nullptr;
temp_node->data = new_data;
if (this == nullptr)
temp_node->prev = nullptr;
node* end_node = this;
while (end_node->next != nullptr)
end_node = end_node->next;
end_node->next = temp_node;
temp_node->prev = end_node;
}
#include"node.h"
int main()
{
node<int> numbers(2);
numbers.AddFront(1);
numbers.AddBack(3);
for (int i = 0; i < numbers.GetSize(); i++)
std::cout << numbers[i] << ' ';
}