This is the constructor for the LinkedList class. It initializes an empty linked list with the head pointer set to `nullptr`.
// Template struct for Node
template <typename T>
struct Node
{
T data; // Data stored in the node
Node<T> *prev; // Pointer to the next node
// Constructor to initialize the node
Node<T>(T value) : data(value), prev(nullptr) {}
};
template <typename T>
LinkedList<T>::LinkedList()
{
this->head = nullptr;
}
// Initializes the head to nullptr, indicating an empty list.
This is the destructor for the LinkedList class. It deallocates all the nodes in the list to free memory, ensuring no memory leaks occur.
template <typename T>
LinkedList<T>::~LinkedList()
{
Node<T> *temp;
while (head) {
temp = head;
head = head->next;
delete temp;
}
}
// Frees memory by deleting all nodes in the list.
The insert method adds a new node with the specified value to the end of the list. It traverses the list and links the new node to the last node.
template <typename T>
void LinkedList<T>::insert(T val)
{
Node<T> *newNode = new Node<T>(val);
if (!head) {
head = newNode;
} else {
Node<T> *temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Inserts a new node with the value `val` at the end of the list.
The deleteNode method removes the node with the given value. It adjusts the links between nodes to maintain the integrity of the list, deleting the node when found.
template <typename T>
bool LinkedList<T>::deleteNode(T val)
{
if (!head) return false;
if (head->data == val) {
Node<T> *temp = head;
head = head->next;
delete temp;
return true;
}
Node<T> *temp = head;
while (temp->next) {
if (temp->next->data == val) {
Node<T> *nodeToDelete = temp->next;
temp->next = temp->next->next;
delete nodeToDelete;
return true;
}
temp = temp->next;
}
return false;
}
// Deletes the node with the given value `val`.
The print method traverses the linked list and prints each node’s data in sequence, separated by arrows ('->') to represent the links between them.
template <typename T>
void LinkedList<T>::print()
{
Node<T> *temp = head;
while (temp) {
std::cout << temp->data;
if (temp->next != nullptr)
std::cout << " -> ";
temp = temp->next;
}
std::cout << std::endl;
}
// Prints the linked list by traversing from head to the last node.
This is the main function, which demonstrates how to create a linked list, insert nodes, delete nodes, and print the list.
#include <iostream>
#include "LinkedList.h"
int main()
{
LinkedList<int> linkedList;
linkedList.insert(1);
linkedList.insert(2);
linkedList.insert(3);
linkedList.print();
linkedList.deleteNode(1);
linkedList.print();
linkedList.deleteNode(2);
linkedList.print();
linkedList.deleteNode(3);
linkedList.print();
return 0;
}
// Demonstrates inserting, deleting, and printing nodes in the linked list.
Comments
Be the first one to comment!