Skip to main content

Types of Linked List

Three types of Linked List​

  • Singly Linked-List
  • Doubly Linked-List
  • Circular Linked-List

A singly linked list is a fundamental data structure, it consists of nodes where each node contains a data field and a reference to the next node in the linked list. The next of the last node is null, indicating the end of the list. Linked Lists support efficient insertion and deletion operations.

Data Structures

singlyLL.cpp

#include <iostream>
using namespace std;

// Node structure
class Node {
public:
int data; // Data stored in the node
Node\* next; // Pointer to the next node

// Constructor
Node(int value) {
data = value;
next = nullptr;
}

};

// Linked List class
class SinglyLinkedList {
private:
Node\* head;

public:
// Constructor
SinglyLinkedList() {
head = nullptr;
}

// Insert at the beginning
void insertAtBeginning(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}

// Insert at the end
void insertAtEnd(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}

Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}

temp->next = newNode;
}

// Delete a node by value
void deleteNode(int value) {
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}

if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}

Node* prev = nullptr;
Node* curr = head;
while (curr != nullptr && curr->data != value) {
prev = curr;
curr = curr->next;
}

if (curr == nullptr) {
cout << "Value not found!" << endl;
return;
}

prev->next = curr->next;
delete curr;
}

// Display the list
void display() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

// Destructor to free memory
~SinglyLinkedList() {
Node* current = head;
while (current != nullptr) {
Node* nextNode = current->next;
delete current;
current = nextNode;
}
}

};

// Main function to test the linked list
int main() {
SinglyLinkedList list;

list.insertAtBeginning(10);
list.insertAtBeginning(20);
list.insertAtEnd(30);
list.insertAtEnd(40);

cout << "Linked List: ";
list.display();

list.deleteNode(20);
cout << "After deleting 20: ";
list.display();

list.deleteNode(100); // Not in list

return 0;

}

output
Linked List: 20 -> 10 -> 30 -> 40 -> NULL
After deleting 20: 10 -> 30 -> 40 -> NULL
Value not found!