#include <iostream>
using namespace std;
struct list
{
int data;
struct list *next,*prev;
};
typedef struct list node;
node *start=NULL;
void insert_node()
{
node *temp,*last;
temp = new node();
cout<<"Insert Data: ";
cin>>temp->data;
temp->next = NULL;
temp->prev = NULL;
if(start==NULL) ///if it is the first node
{
start= new node();
start->data= temp->data;
start->next=NULL;
start->prev=NULL;
}
else
{
last =start;
while(last->next!= NULL)
{
last = last->next;
}
last->next = temp;///save data in last node
temp->prev=last;
}
}
void display() ///print the function
{
node *temp = start;
cout<<"Main Linked List: "<<endl;
while(temp!= NULL)
{
cout<<temp->data<< " ";
temp = temp -> next;
}
cout<<endl;
}
void reverse()
{
node * temp = start,*last;
while(temp->next != NULL) ///find the last node
{
temp = temp->next;
}
last = temp; ///save last node to another node
cout<<"Reverse : "<<endl;
while(last!=NULL)
{
cout<<last->data<< " ";
last = last->prev;
}
cout<<endl;
}
int main()
{
int flag=1;
while(flag==1)
{
cout<<"Press 1 to Enter Node: ";
cin>>flag;
if(flag!=1)break;
insert_node();
}
display(); ///print function
reverse(); ///print reverse
return 0;
}
Output
Press 1 to Enter Node: 1
Insert Data: 1
Press 1 to Enter Node: 1
Insert Data: 2
Press 1 to Enter Node: 1
Insert Data: 3
Press 1 to Enter Node: 0
Main Linked List:
1 2 3
Reverse :
3 2 1
Add your comment