Reverse a singly Linked List

 


#include<bits/stdc++.h>

using namespace std;


struct Node

{

    int data;

    struct Node *Next;

};

int main()

{

    int arr[]= {1,2,3,4,5};

    struct Node *temp,*Head=NULL,*current=NULL;

    //insert data from array

    for(int i=0; i<5; i++)

    {

        temp= (struct Node *)malloc(sizeof(struct Node));

        temp->data=arr[i];

        temp->Next=NULL;

        if(Head==NULL)

        {

            Head=temp;

            current=temp;

        }

        else

        {

            //current=temp;

            current->Next=temp;

            current=current->Next;

        }

    }

    //Reverse a singly Linked List

    struct Node *crnt, *prvs, *nxt;

    crnt=Head;

    prvs=NULL;

    while(crnt!=NULL)

    {

        cout<<crnt->data<<endl;

        nxt=crnt->Next;

        crnt-> Next=prvs;

        prvs=crnt;

        crnt=nxt;

    }

    //print link list

    Head=prvs;

    while(Head!=NULL)

    {


        cout<<Head->data<<endl;

        Head=Head->Next;

    }


}


Comments