Q.) REVERSE A SINGLY LINK LIST .
example--
link list={1,2,3,4,5,6,7}
output link list={7,6,5,4,3,2,1}
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct node
{
int data;
struct node *next;
}*head;
struct node *temp;
int num,i,item;
head=NULL;
printf("enter number of nodes of link list=");
scanf("%d",&num);
//creation of singly link list//
for(i=0;i<num;i++)
{
scanf("%d",&item);
if(head==NULL)
{
head=malloc(sizeof(struct node));
head->data=item;
//printf("%d ",head->data);
temp=head;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=item;
temp=temp->next;
}
}
temp->next=NULL;
temp=head;
struct node *prevn = NULL; //previous node
struct node *currn = head; //current node
struct node *nextn = NULL; //next node
//In the loop, we need to change NextN to PrevN, PrevN to
//CurrN and CurrN to NextN
currn=head;
//printf("%d ",head->data);
while (currn!= NULL)
{
nextn = currn->next;
currn->next = prevn;
prevn = currn;
currn = nextn;
}
temp=prevn;
while(prevn!=NULL)
{
printf("%d ",prevn->data);
prevn=prevn->next;
}
}
example--
link list={1,2,3,4,5,6,7}
output link list={7,6,5,4,3,2,1}
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct node
{
int data;
struct node *next;
}*head;
struct node *temp;
int num,i,item;
head=NULL;
printf("enter number of nodes of link list=");
scanf("%d",&num);
//creation of singly link list//
for(i=0;i<num;i++)
{
scanf("%d",&item);
if(head==NULL)
{
head=malloc(sizeof(struct node));
head->data=item;
//printf("%d ",head->data);
temp=head;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=item;
temp=temp->next;
}
}
temp->next=NULL;
temp=head;
struct node *prevn = NULL; //previous node
struct node *currn = head; //current node
struct node *nextn = NULL; //next node
//In the loop, we need to change NextN to PrevN, PrevN to
//CurrN and CurrN to NextN
currn=head;
//printf("%d ",head->data);
while (currn!= NULL)
{
nextn = currn->next;
currn->next = prevn;
prevn = currn;
currn = nextn;
}
temp=prevn;
while(prevn!=NULL)
{
printf("%d ",prevn->data);
prevn=prevn->next;
}
}
No comments:
Post a Comment