Write a program in c++ and implement all basic operation (create new node, search element in list, delete from list etc) in doubly linked list
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node* prev;
};
void push(Node** hd_ref, int new_d)
{
Node* n = new Node();
n->data = new_d;
n->next = (*hd_ref);
n->prev = NULL;
if ((*hd_ref) != NULL)
(*hd_ref)->prev = n;
(*hd_ref) = n;
}
void insertAfter(Node* pv_node, int n_data)
{
if (pv_node == NULL)
{
cout<<"Cannot be NULL";
return;
}
Node* n = new Node();
n->data = n_data;
n->next = pv_node->next;
pv_node->next = n;
n->prev = pv_node;
if (n->next != NULL)
n->next->prev = n;
}
void append(Node** hd_ref, int new_d)
{
Node* n = new Node();
Node* ls = *hd_ref;
n->data = new_d;
n->next = NULL;
if (*hd_ref == NULL)
{
n->prev = NULL;
*hd_ref = n;
return;
}
while (ls->next != NULL)
ls = ls->next;
ls->next = n;
n->prev = ls;
return;
}
void display(Node* nd)
{
Node* lt;
cout<<"\nForward direction \n";
while (nd != NULL)
{
cout<<" "<<nd->data<<" ";
lt = nd;
nd = nd->next;
}
cout<<"\nReverse direction \n";
while (lt != NULL)
{
cout<<" "<<lt->data<<" ";
lt = lt->prev;
}
}
int main()
{
Node* hd = NULL;
append(&hd, 1);
push(&hd, 2);
push(&hd, 3);
append(&hd, 4);
insertAfter(hd->next, 5);
cout << "DLL: ";
display(hd);
return 0;
}
Comments
Leave a comment