Skip to content

Instantly share code, notes, and snippets.

@na5imuzzaman
Created July 17, 2017 06:57
Show Gist options
  • Save na5imuzzaman/da8e16985ee681a65c20f253dce3a30f to your computer and use it in GitHub Desktop.
Save na5imuzzaman/da8e16985ee681a65c20f253dce3a30f to your computer and use it in GitHub Desktop.
Doubly Linked List Implementation Using C++
/* Nasim */
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *prev;
node *next;
};
node *Ehead = NULL;
node* NewNode(int n)
{
node *root = new node();
root->data = n;
root->next = NULL;
root->prev = NULL;
return root;
}
void InsertAtHead(int n,node **head)
{
node* root = NewNode(n);
if ((*head) == NULL)
{
(*head) = root;
Ehead = root;
return;
}
(*head)->prev = root;
root->next = (*head);
(*head) = root;
}
void InsertAtEnd(int n,node **head,node **temp)
{
node *root = NewNode(n);
if ((*head) == NULL)
{
(*head) = root;
}
else
{
(*temp) = (*head);
while ((*temp)->next != NULL)
{
(*temp) = (*temp)->next;
}
root ->prev = (*temp);
(*temp)->next = root;
Ehead = root;
}
}
void print(node *head)
{
cout<<"Forward:\n";
node *root = head;
while(root != NULL)
{
cout<<root->data<<" ";
root = root->next;
}
}
void reprint()
{
cout<<"Reverse:\n";
node *root = Ehead;
while (root != NULL)
{
cout<<root->data<<" ";
root = root->prev;
}
}
int main()
{
node *head = NULL,*temp = NULL;
InsertAtHead(34,&head);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtHead(44,&head);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtHead(37,&head);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtEnd(94,&head,&temp);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtHead(3,&head);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtEnd(100,&head,&temp);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
InsertAtHead(4,&head);
print(head);
cout<<"\n";
reprint();
cout<<"\n\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment