Note: No global declarations
Call the functions in main through menu
Implement the following :
Singly Linked List with following functions :
1)insert_at_head(node* & head, int val);
2)insert_at_tail(node* & head, int val);
3)display(node* head) ;
4)insert_at_pos(node* & head, int val,int pos);
5)delete_at_head(node* & head);
6)delete_at_tail(node* & head);
7)delete_at_pos(node* & head, int pos);
#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