#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void insertAtBeggining(struct Node** head, int newD)
{
struct Node* newNode = new Node;
newNode->data = newD;
newNode->next = (*head);
newNode->prev = NULL;
if ((*head) != NULL)
(*head)->prev = newNode;
(*head) = newNode;
}
void insertAfter(struct Node* prevN, int newD)
{
if (prevN == NULL) {
cout<<"Previous node cannot be NULL";
return;
}
struct Node* newNode = new Node;
newNode->data = newD;
newNode->next = prevN->next;
prevN->next = newNode;
newNode->prev = prevN;
if (newNode->next != NULL)
newNode->next->prev = newNode;
}
void insertAtEnd(struct Node** head, int newD)
{
struct Node* newNode = new Node;
struct Node* L = *head;
newNode->data = newD;
newNode->next = NULL;
if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
}
while (L->next != NULL)
L = L->next;
L->next = newNode;
newNode->prev = L;
return;
}
void displayList(struct Node* node) {
struct Node* L;
while (node != NULL) {
cout<<node->data<<"<==>";
L = node;
node = node->next;
}
if(node == NULL)
cout<<"NULL";
}
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 4);
insertAtBeggining(&head, 2);
insertAtBeggining(&head, 1);
insertAtEnd(&head, 5);
insertAfter(head->next, 3);
cout<<"Doubly linked list: "<<endl;
displayList(head);
return 0;
}
Comments
Leave a comment