Created
October 27, 2025 13:37
-
-
Save ukor/d5d13a6dae9e6afccf75367d462a2f03 to your computer and use it in GitHub Desktop.
Linked List with C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Online C++ compiler to run C++ program online | |
| #include <iostream> | |
| using namespace std; | |
| struct Node { | |
| int data; | |
| Node* next; | |
| Node* prev; | |
| Node(int value): data(value), next(nullptr), prev(nullptr) {} | |
| }; | |
| class DoubleLinkedList { | |
| public: | |
| Node* head; | |
| Node* tail; | |
| DoubleLinkedList(): head(nullptr), tail(nullptr) {} | |
| void insert(int value) { | |
| Node* newNode = new Node(value); | |
| if(!head) { | |
| head = tail = newNode; | |
| return; | |
| } | |
| tail->next = newNode; | |
| newNode->prev = tail; | |
| tail = newNode; | |
| } | |
| // Display from head to tail | |
| void displayForward() { | |
| Node* tmp = head; | |
| while(tmp) { | |
| cout << tmp->data << " <-> "; | |
| tmp = tmp->next; | |
| } | |
| cout << "NULL" << endl; | |
| } | |
| void displayBackward() { | |
| Node* tmp = tail; | |
| while(tmp) { | |
| cout << tmp->data << " -> "; | |
| tmp = tmp->prev; | |
| } | |
| cout << "NULL" << endl; | |
| } | |
| }; | |
| int main() { | |
| DoubleLinkedList list; | |
| list.insert(10); | |
| list.insert(20); | |
| list.insert(30); | |
| list.insert(40); | |
| list.insert(50); | |
| cout << "Forward traversal: "; | |
| list.displayForward(); | |
| cout << "Backward traversal: "; | |
| list.displayBackward(); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| struct Node { | |
| int data; | |
| Node* next; | |
| Node(int value): data(value), next(nullptr) {} | |
| }; | |
| class SingleLinkedList { | |
| public: Node* head; | |
| SingleLinkedList(): head(nullptr) {} | |
| void insert(int value) { | |
| Node* newNode = new Node(value); | |
| if(!head) { | |
| head = newNode; | |
| return; | |
| } | |
| Node* tmp = head; | |
| while(tmp->next) { | |
| tmp = tmp->next; | |
| } | |
| tmp->next = newNode; | |
| } | |
| void display() { | |
| Node* tmp = head; | |
| while(tmp) { | |
| cout << tmp->data << " -> "; | |
| tmp = tmp->next; | |
| } | |
| cout << "NULL" << endl; | |
| } | |
| }; | |
| int main() { | |
| SingleLinkedList list; | |
| list.insert(10); | |
| list.insert(20); | |
| list.insert(30); | |
| list.insert(40); | |
| list.display(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment