Reverse a singly link list in C data structure
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *create_link_list(int arr[],int size)
{
struct node *temp=NULL,*head=NULL,*current=NULL;
for(int i=0;i<size;i++)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=arr[i];
temp->next=NULL;
if(head==NULL)
{
head=temp;
current=temp;
}
else
{
current->next=temp;
current=temp;
}
}
return head;
};
struct node *reverse(struct node *head)
{
struct node *prev=NULL,*current=head,*next=NULL;
while(current!=NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
head=prev;
return head;
}
int main()
{
int n;
printf("Enter array size : ");
scanf("%d",&n);
int arr[n];
printf("Enter array element : ");
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
struct node *head;
head= create_link_list(arr,n);
head=reverse(head);
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
}
0 Comments