So I missed todays lecture about linked lists due to being ill. But a classmate sent me the assignment.
Fighting throught the illnes by cycling sleep with doing assignment.
Have 3 tasks on the assignment
task 1: make a singly linked list with these functions:
Prepend(value)
Append(value)
Clear()
PopFront()
PopBack()
PrintItems()
task 2: implement a doubly linked list class with the same functions as in task 1
task 3: use templates to allow construction of a linked list containing any data type
I've finshed task 1, think I'm not leaking any memory
Node.h (made 2 constructors and Node* prev so I wont have to make a whole new Node class for task 2)
Code: Select all
#pragma once
class Node
{
public:
Node(Node* next_in, int value_in);
Node(Node* next_in, Node* prev_in, int value_in);
Node* next = nullptr;
Node* prev = nullptr;
int value;
};
Code: Select all
#include "Node.h"
Node::Node(Node * next_in, int value_in)
:
next(next_in),
prev(nullptr),
value(value_in)
{}
Node::Node(Node * next_in, Node * prev_in, int value_in)
:
next(next_in),
prev(prev_in),
value(value_in)
{}
Code: Select all
#pragma once
#include "Node.h"
#include <iostream>
class SinglyLinkedList
{
public:
SinglyLinkedList();
~SinglyLinkedList();
void Prepend(int value_in);
void Append(int value_in);
void Clear();
void PopFront();
void PopBack();
void PrintItems();
private:
Node* m_First = nullptr;
};
Code: Select all
#include "SinglyLinkedList.h"
SinglyLinkedList::SinglyLinkedList()
{
m_First = nullptr;
}
SinglyLinkedList::~SinglyLinkedList()
{
Clear();
delete m_First;
}
void SinglyLinkedList::Prepend(int value_in)
{
m_First = new Node(m_First, value_in);
}
void SinglyLinkedList::Append(int value_in)
{
if (!m_First)
{
Prepend(value_in);
}
else
{
Node* node;
for (node = m_First; node->next; node = node->next);
node->next = new Node(nullptr, value_in);
}
}
void SinglyLinkedList::Clear()
{
if (m_First)
{
Node* curNode = m_First;
Node* prevNode = nullptr;
while (curNode)
{
prevNode = curNode;
curNode = curNode->next;
delete prevNode;
prevNode = nullptr;
}
}
}
void SinglyLinkedList::PopFront()
{
if (m_First)
{
if (m_First->next)
{
Node* first = m_First;
m_First = m_First->next;
delete first;
first = nullptr;
}
else
{
delete m_First;
m_First = nullptr;
}
}
}
void SinglyLinkedList::PopBack()
{
if (m_First)
{
if (m_First->next)
{
Node* last = m_First;
Node* prev = m_First;
for (; last->next; prev = last, last = last->next);
delete last;
last = nullptr;
prev->next = nullptr;
}
else
{
delete m_First;
m_First = nullptr;
}
}
}
void SinglyLinkedList::PrintItems()
{
if (!m_First)
{
std::cout << "List is empty.\n";
}
else
{
for (Node* i = m_First; i; i = i->next)
{
std::cout << i->value << std::endl;
}
}
}