Showing posts with label Doubly linked list. Show all posts
Showing posts with label Doubly linked list. Show all posts

Wednesday 16 September 2015

Doubly linked list

#include <iostream>

using namespace std;
struct node
{
    int data;
    node* next;
    node* previous;
};

node* head;
void insert(int x)
{
    node* temp=new node();
    temp->data=x;
    if(head==NULL)
    {
        head=temp;
        head->next=NULL;
        head->previous=NULL;
    }
    else

    temp->next=head;
    head->previous=temp;
    head=temp;
}
void showstart()
{
   node* temp1=head;
   while(temp1!=NULL)
   {
       cout<<temp1->data<<"->";
       temp1=temp1->next;
   }
   cout<<"NULL"<<endl;
}
void showend()
{
    node* temp2=head;
    while(temp2->next!=NULL)
    {
        temp2=temp2->next;
    }

    while(temp2!=head)
    {
        cout<<temp2->data<<"->";
        temp2=temp2->previous;
    }
    cout<<head->data;

}
int main()
{
    head=NULL;
    int n,x;
    cout<<"How many elements do you want to enter?"<<endl;
    cin>>n;
    while(n--)
      {
          cout<<"Enter data :";
          cin>>x;
          insert(x);
      }
cout<<"Doubly linked list from the start is :"<<endl;
showstart();

cout<<"Doubly linked list from the end is:"<<endl;
showend();
}