C Program to reverse an ordered linked list for Data Structure for C Program

C Program to reverse an ordered linked list:

struct node
{
inf info;
struct node *link;
};typedef struct node sn;
sn*insert(sn *root, int i)
{
sn *new,*temp,*ptemp;
new=(sn*)malloc(sizeof(sn));
if(new= =NULL)
{
printf(“Memory allocation error…”);
exit(0);
}
new->info=I;new->link=NULL;
if(root= =NULL)
root=new;
else
if(i<root->info)
{
new->link=root;  root=new;
}
else
{
temp=root;
while(temp=NULL&&i>temp->info)
{
ptemp=temp;
temp=temp->link;
}
new->link=temp;
ptemp->link=new;
}return root; /*address of first node is returned*/
}
void traverse(sn *ptr)
{
while(ptr!=NULL)
{
printf(“%d”,ptr->info); ptr=ptr->link;
}
}
sn*reversell(sn *root)
{
sn *first=root,*pptr=root,*nptr;
nptr=nptr->link;
while(nptr!=NULL)
{
root=nptr;
nptr=nptr->link;
root->link=pptr;
pptr=root;
}
first->link=NULL;
return root;
}
main()
{
sn *root=NULL,*ptr;int info; char ch;
while(1)
{
printf(“/nEnter node information :”);
scanf(“%d”,&info);
root=insert(root,info);
printf(“\n Do you want to continue…(y/n)”);
ch=getche();
if(ch!=’y’)
 break;
}
printf(“\nOrdered (Asc)Singly Linked List :\n\n”);
treverse(root);getch();
printf(“\n\n The reversed (desc)linked list :\n\n”);
root=reversell(root);
traverse(root); getch();
}

The same reversing function also can be applied to the circular linked list by just changing the required condition to test the last node’s link. In normal linked list it is NULL. In circular linked list it become the address of the first node itself, stored in external pointer(root).

C Program to reverse an ordered linked list for Data Structure for C Program C Program to reverse an ordered linked list for Data Structure for C Program Reviewed by Jackrin Reacher on February 27, 2014 Rating: 5

No comments