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

Monday 21 September 2015

Reversal of linked list

#include <iostream>
using namespace std;
struct node
          {
             int data ;
             node* next;
          };


node* head;
void reverse()
        {

             node* previous;
             node* current;
             node* front;
             previous=current=front=head;
                 while(front!=NULL)
                      {

                           if(current==head)
                             {

                                   front=current->next;
                                   current->next=NULL;

                              }
                           current=front;
                           front=current->next;
                           current->next=previous;
                           previous=current;
                      }

            head=current;

   }

void push(int x)
    {   

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


void show()

node*temp1=head;

while(temp1!=NULL)

      {

            cout<<temp1->data<<"->";
            temp1=temp1->next;
       }

  cout<<"NULL"<<endl;
    }


int main()
{

    head=NULL;
    int x;
    int n;
    cout<<"How many elements do you want to enter";
    cin>>n;
    while(n--)
    {

         cout<<"Enter data";
         cin>>x;
         push(x);
      }
    cout<<"The linked list is"<<endl;
   
    show();
    reverse();
    cout<<"The reversed linked list is"<<endl;
    show();

}