Implement the code of Doubly Linked List.
Add your roll # node using Append function.
Add the last two digits of your contact # using Prepend function
Add your favorite digit between roll # and contact #.
And display the doubly linked list.
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int d;
Node* nxt;
Node* prev;
};
void push(Node** h_ref, int n_data)
{
Node* n_node = new Node();
n_node->d = n_data;
n_node->nxt = (*h_ref);
n_node->prev = NULL;
if ((*h_ref) != NULL)
(*h_ref)->prev = n_node;
(*h_ref) = n_node;
}
void insert(Node* pv_node, int n_data)
{
if (pv_node == NULL)
{
cout<<"the given previous node cannot be NULL";
return;
}
Node* n_node = new Node();
n_node->d = n_data;
n_node->nxt = pv_node->nxt;
pv_node->nxt = n_node;
n_node->prev = pv_node;
if (n_node->nxt != NULL)
n_node->nxt->prev = n_node;
}
void append(Node** h_ref, int n_data)
{
Node* n_node = new Node();
Node* last = *h_ref;
n_node->d = n_data;
n_node->nxt = NULL;
if (*h_ref == NULL)
{
n_node->prev = NULL;
*h_ref = n_node;
return;
}
while (last->nxt != NULL)
last = last->nxt;
last->nxt = n_node;
n_node->prev = last;
return;
}
void display(Node* node)
{
Node* last;
cout<<"\nTraversal in forward direction \n";
while (node != NULL)
{
cout<<" "<<node->d<<" ";
last = node;
node = node->nxt;
}
cout<<"\nTraversal in reverse direction \n";
while (last != NULL)
{
cout<<" "<<last->d<<" ";
last = last->prev;
}
}
int main()
{
Node* h = NULL;
append(&h, 1);
push(&h, 2);
push(&h, 3);
append(&h, 4);
insert(h->nxt, 5);
cout << "Created DLL is: ";
display(h);
return 0;
}
Comments
Leave a comment