Doubly Linked List
Doubly Linked List
Code Implementation
#include <iostream>
class Node {
public:
int data;
Node* prev;
Node* next;
Node(int value) {
data = value;
prev = nullptr;
next = nullptr;
};
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList() {
head = nullptr;
if (head != nullptr) {
head->prev = newNode;
newNode->next = head;
head = newNode;
if (head == nullptr) {
head = newNode;
return;
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
temp = temp->next;
if (temp == nullptr) {
cout << "Node with value " << key << " not found.\n";
return;
newNode->next = temp->next;
newNode->prev = temp;
if (temp->next != nullptr) {
temp->next->prev = newNode;
temp->next = newNode;
void deleteFromBeginning() {
if (head == nullptr) {
return;
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
delete temp;
void deleteFromEnd() {
if (head == nullptr) {
return;
if (head->next == nullptr) {
delete head;
head = nullptr;
return;
temp->prev->next = nullptr;
delete temp;
// 6. Delete by value
if (head == nullptr) {
return;
if (head->data == value) {
deleteFromBeginning();
return;
temp = temp->next;
if (temp == nullptr) {
cout << "Value " << value << " not found in the list.\n";
return;
if (temp->next != nullptr) {
temp->next->prev = temp->prev;
if (temp->prev != nullptr) {
temp->prev->next = temp->next;
delete temp;
temp = temp->next;
return false;
void displayForward() {
if (head == nullptr) {
return;
temp = temp->next;
void displayReverse() {
if (head == nullptr) {
return;
temp = temp->next;
temp = temp->prev;
};
int main() {
DoublyLinkedList list;
list.insertAtBeginning(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAfter(20, 25);
list.displayForward();
list.displayReverse();
list.deleteFromBeginning();
list.displayForward();
list.deleteFromEnd();
list.displayForward();
list.deleteByValue(25);
list.displayForward();
if (list.search(20)) {
} else {
return 0;
1. **Class `Node`**:
- Represents a node with data, a pointer to the previous node, and a pointer to the
next node.
2. **Class `DoublyLinkedList`**:
3. **Insertion Methods**:
4. **Deletion Methods**:
5. **Search Method**:
- Searches for a specific element in the list.
6. **Display Methods**:
7. **Main Function**:
Sample Output```
```
---
This code provides all essential operations for a **Doubly Linked List** with
clear examples. You can further customize it for additional functionality, like
sorting or merging two lists.