I created a simple linked list to test what I've learned so far and if I manage everything correctly. If you see syntax errors is't because of copy-paste. I just want to know if i'm making everything in the right way without having leak and memory problems.
Node
class
#include "Node.h"
//Constructor.
Node::Node(int v)
:next(nullptr), value(v)
{
}
//Deconstrucor (not in use).
Node::~Node()
{
}
//Set next.
void Node::set_next(Node *new_node)
{
this -> next = new_node;
}
//Set previous.
void Node::set_prev(Node *new_node)
{
this -> prev = new_node;
}
//Set value.
void Node::set_value(int v)
{
this -> value = v;
}
//Get next.
Node *Node::get_next()
{
return this -> next;
}
//Get previous.
Node *Node::get_prev()
{
return this -> prev;
}
//Get value
int Node::get_value()
{
return this -> value;
}
LinkedList
class
#include "LinkedList.h"
#include "Node.h"
#include <new>
#include <iostream>
//Constructor.
LinkedList::LinkedList()
:head(nullptr), tail(nullptr), moving_ptr(nullptr)
{
}
//Deconstrucor (not in use).
LinkedList::~LinkedList()
{
}
//Append a new item on the list.
void LinkedList::append(int v)
{
//Allocate a new node.
Node *new_node = new (std::nothrow)Node(v);
//If memory is full, exit the program.
if (new_node == nullptr){
std::cout << "Memory is full, program will exit." << std::endl;
exit(0);
}
//If this is the first node.
if (head == nullptr || tail == nullptr)
{
head = new_node;
tail = new_node;
moving_ptr = new_node;
}
//Append other node.
else
{
tail -> set_next(new_node); //Link it after the tail of the list.
new_node -> set_prev(tail); //Set the previous node.
tail = new_node; //Update the tail pointer.
}
}
//Remove a node from the list.
bool LinkedList::remove_item(int v)
{
//Starting node.
Node *curr = head;
//----Find the node that contains v----//
while (curr != nullptr)
{
//Found.
if (curr -> get_value() == v)
break;
//Keep going.
else
curr = curr -> get_next();
}
//----Find the node that contains v----//
//The item was not found into the list.
if (curr == nullptr)
return false;
//Make necessary links!!!
curr -> get_prev() -> set_next( curr -> get_next() );
//Delete current node.
delete curr;
return true;
}
//Get the next item.
int LinkedList::nextItem()
{
//Temp that hold current value.
int temp = moving_ptr -> get_value();
//Move to the next node.
moving_ptr = moving_ptr -> get_next();
//Return the value.
return temp;
}
//Return true if moving_ptr is not null.
bool LinkedList::hasNext()
{
return moving_ptr != nullptr;
}
//Reset moving_ptr.
void LinkedList::reset()
{
moving_ptr = head;
}
Am I handling everything correctly? I also tried to fill all my memory with an infinite loop to see what happens and everything run's smoothly. The program terminates when memory is full.