Implementation of Doubly Linked List in C++
#include<iostream>
using namespace std;
using namespace std;
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
struct Node *head = NULL; //global variable-pointer to head node.
struct Node *tail = NULL; //global variable-pointer to tail node.
void createNode()
{
struct Node *newnode = new Node;
if (tail==NULL&&head==NULL)
{
cout<<"Enter Data: ";
cin>>newnode->data;
newnode->prev=NULL;
newnode->next=NULL;
head=newnode;
tail=newnode;
}
else
{
cout<<"Enter Data: ";
cin>>newnode->data;
newnode->prev=head;
newnode->next=NULL;
head->next=newnode;
head=newnode;
}
}
void displayForward()
{
//Local supporting node
struct Node *temp;
temp=tail;
cout<<"Printing Forward: ";
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
cout<<endl;
}
void displayReverse()
{
//Local supporting node
struct Node *temp;
temp=head;
cout<<"Printing Backward: ";
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->prev;
}
cout<<endl;
}
void insertAtTail()
{
struct Node *newnode = new Node;
if (tail==NULL&&head==NULL)
{
cout<<"Enter Data: ";
cin>>newnode->data;
newnode->prev=NULL;
newnode->next=NULL;
head=newnode;
tail=newnode;
}
else
{
cout<<"Enter Data: ";
cin>>newnode->data;
newnode->prev=NULL;
newnode->next=tail;
tail->prev=newnode;
tail=newnode;
}
}
int main()
{
insertAtTail(); displayReverse(); displayForward();
createNode(); displayReverse(); displayForward();
insertAtTail(); displayReverse(); displayForward();
createNode(); displayReverse(); displayForward();
createNode(); displayReverse(); displayForward();
insertAtTail(); displayReverse(); displayForward();
insertAtTail(); displayReverse(); displayForward();
//Write your code for menu driven here & remove all function calls from above....
return 0;
}
No comments
Post your comments