#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class Node {
public :
int data;
Node *next;
Node *prev;
Node() {
data = 0;
next = NULL;
prev = NULL;
}
Node(int data) {
this->data = data;
this->next = NULL;
this->prev = NULL;
}
};
class DoublyLinkedList {
Node *head;
public :
DoublyLinkedList() {
head = NULL;
}
void insertDataAtTheFront(int);
void insertDataAtTheEnd(int);
void insertAtPosition(int, int, DoublyLinkedList*);
void printList();
};
void DoublyLinkedList::insertAtPosition(int data, int position, DoublyLinkedList* dll) {
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
return;
}
if(position == 1) {
dll->insertDataAtTheFront(data);
return;
}
Node *temp = head;
Node *prev;
while(position-- > 1 ) {
temp = temp->next;
}
if(temp == NULL) {
//cout << "position " << position << " is beyond the length of the list" << endl;
return;
}
// newNode->prev = temp->prev;
// newNode->next = temp;
// prev->next=newNode;
prev = temp->prev;
newNode->next = temp;
temp->prev = newNode;
newNode->prev = prev;
prev->next = newNode;
}
void DoublyLinkedList::insertDataAtTheFront(int data) {
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
return;
}
// newNode->next = head->next;
Node *temp = head;
newNode->next = temp;
temp->prev = newNode;
head = newNode;
}
void DoublyLinkedList::insertDataAtTheEnd(int data) {
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
return;
}
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
void DoublyLinkedList::printList() {
Node *temp = head;
Node *lastNode = NULL;
cout << "Traversing in forward direction : " << endl;
while (temp != NULL) {
cout << temp->data << endl;
lastNode = temp;
temp = temp->next;
}
cout << "Traversing in backward direction : " << endl;
while (lastNode != NULL) {
cout << lastNode->data << endl;
lastNode = lastNode->prev;
}
}
int main() {
cout << "Hello World!" <<endl;
DoublyLinkedList *doublyLinkedList = new DoublyLinkedList();
doublyLinkedList->insertDataAtTheFront(2);
doublyLinkedList->insertDataAtTheEnd(3);
doublyLinkedList->insertAtPosition(11, 1, doublyLinkedList);
doublyLinkedList->insertAtPosition(12, 3, doublyLinkedList);
doublyLinkedList->insertAtPosition(13, 3, doublyLinkedList);
doublyLinkedList->printList();
return 0;
}