Implementation of Double link list in c++
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
Node* prev;
};
Node* first = NULL;
Node* last = NULL;
void insertAtLast(int val)
{
Node* new_node = new Node;
new_node->data = val;
if (last == NULL)
{
new_node->next = new_node->prev = NULL;
first = last = new_node;
}
else
{
new_node->next = NULL;
new_node->prev = last;
last->next = new_node;
last = new_node;
}
}
void insertAtFirst(int val)
{
Node* new_node = new Node;
new_node->data = val;
if (first == NULL)
{
new_node->next = new_node->prev = NULL;
first = last = new_node;
}
else
{
new_node->prev = NULL;
new_node->next = first;
first->prev = new_node;
first = new_node;
}
}
void traverseFirst()
{
Node* new_node = new Node;
new_node = first;
while (new_node != NULL)
{
cout << new_node->data << " ";
new_node = new_node->next;
}
cout << endl;
}
void traverseLast()
{
Node* new_node = new Node;
new_node = last;
while (new_node != NULL)
{
cout << new_node->data << " ";
new_node = new_node->prev;
}
cout << endl;
}
void deletefirst()
{
Node* new_node = new Node;
new_node = first;
if (new_node == NULL)
{
cout << "List Empty" << endl;
return;
}
first = first->next;
if (first != NULL)
{
first->prev = NULL;
}
delete new_node;
}
void deletelast()
{
Node* new_node = new Node;
new_node = last;
if (new_node == NULL)
{
cout << "List Empty" << endl;
return;
}
last = last->prev;
if (last != NULL)
{
last->next = NULL;
}
delete new_node;
}
int main()
{
insertAtLast(10);
insertAtFirst(20);
traverseFirst();
deletefirst();
traverseLast();
deletelast();
traverseLast();
cout << endl;
return 0;
}
Comments
Post a Comment