C Program to Reverse a Linked List

A connected rundown can be turned around by altering the course of the

the pointer, iteratively.

The calculation for turning around the connected rundown

Give us a chance to take three-pointer factors P, q and r.

P references the connected rundown turned around up until now, q focuses on

the connected rundown to be switched and r focuses to the following hub of q.

while(all hubs have not been turned around )

{

Turn around

the hub pointed by q.

q->next=P;

move P,

q, r forward by a hub.

P=q;

q=r;

r=r->next;

}

C Program to Reverse a Linked List

``````#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
int data;
struct node *next;
}node;

node *create(int);
void print(node *);
node *invert(node *);

int main()
{
int n;
printf(“Enter how many nodes? “);
scanf(“%d”,&n);
printf(“nEnter nodes: “);

print(P);

return 0;
}

node* create(int n)
{
int i;

//create subsequent nodes
for(i=1;i<n;i++)
{
P->next=(node*)malloc(sizeof(node));
//new node is inserted as the next node after P
P=P->next;
scanf(“%d”,&(P->data));
P->next=NULL;
}
}

void print(node *P)
{
while(P!=NULL)
{
printf(“<- %d ->”,P->data);
P=P->next;
}
}

{
node *P,*q,*r;

//initial  values of P, q and r
P=NULL;
r=q->next;

//until all nodes have reversed
while(q!=NULL)
{
q->next=P;
P=q;
q=r;

if(r!=NULL)
r=r->next;
}

return(P);
}``````

Output