#include <iostream>
// Node structure
struct Node {
int data;
Node* next;
Node(int data) : data(data), next(nullptr) {}
};
// Singly Linked List class
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
// Destructor to free memory
~LinkedList() {
Node* current = head;
Node* nextNode;
while (current != nullptr) {
nextNode = current->next;
delete current;
current = nextNode;
// Add node to the end of the list
void append(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
temp->next = newNode;
// Add node to the beginning of the list
void prepend(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
// Delete node by value
void deleteValue(int value) {
Node* current = head;
Node* previous = nullptr;
// If head node itself holds the value to be deleted
if (current != nullptr && current->data == value) {
head = current->next;
delete current;
return;
}
// Search for the value to be deleted
while (current != nullptr && current->data != value) {
previous = current;
current = current->next;
// If value was not found in the list
if (current == nullptr) return;
// Unlink the node from the linked list
previous->next = current->next;
delete current;
// Print all nodes in the list
void printList() const {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " -> ";
temp = temp->next;
std::cout << "nullptr" << std::endl;
};
int main() {
LinkedList list;
// Add nodes
list.append(10);
list.append(20);
list.prepend(5);
list.prepend(1);
std::cout << "Linked List: ";
list.printList();
// Delete a node
list.deleteValue(20);
std::cout << "Linked List after deleting 20: ";
list.printList();
return 0;
Output
Linked List: 1 -> 5 -> 10 -> 20 -> nullptr
Linked List after deleting 20: 1 -> 5 -> 10 -> nullptr