Single LinkedList
Single LinkedList
Here is a complete C++ program that implements all essential operations of a **Singly Linked
List**, such as:
C++ Code
#include <iostream>
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = nullptr;
newNode->next = head;
head = newNode;
if (head == nullptr) {
head = newNode;
return;
temp = temp->next;
temp->next = newNode;
temp = temp->next;
}
if (temp == nullptr) {
cout << "Node with value " << key << " not found.\n";
return;
newNode->next = temp->next;
temp->next = newNode;
void deleteFromBeginning() {
if (head == nullptr) {
return;
head = head->next;
delete temp;
void deleteFromEnd() {
if (head == nullptr) {
return;
if (head->next == nullptr) {
delete head;
head = nullptr;
return;
temp = temp->next;
delete temp->next;
temp->next = nullptr;
// 6. Delete by value
if (head == nullptr) {
return;
if (head->data == value) {
head = head->next;
delete temp;
return;
temp = temp->next;
if (temp->next == nullptr) {
cout << "Value " << value << " not found in the list.\n";
return;
temp->next = temp->next->next;
delete toDelete;
temp = temp->next;
return false;
void display() {
if (head == nullptr) {
return;
temp = temp->next;
}
cout << "NULL\n";
};
int main() {
LinkedList list;
list.insertAtBeginning(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAfter(20, 25);
list.display();
list.deleteFromBeginning();
list.display();
list.deleteFromEnd();
list.display();
list.deleteByValue(25);
list.display();
if (list.search(20)) {
return 0;
1. **Class `Node`**:
- Represents a single node containing data and a pointer to the next node.
2. **Class `LinkedList`**:
3. **Insertion Methods**:
- **After a given value**: Finds a node and inserts a new node after it.
4. **Deletion Methods**:
5. **Search Method**:
6. **Display Method**:
7. **Main Function**: