Program
: Reversing a linked list
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct
link
{
int no;
struct link *next;
};
struct
link *node,*start,*pre,*current,*counter,*p;
int i;
void
create_link(struct link *node);
void
display(struct link *node);
struct
link *reverse(struct link *next);
void
main()
{
clrscr();
node=(struct link *)malloc(sizeof(struct
link));
p=(struct link *)malloc(sizeof(struct
link));
create_link(node);
printf("\n List before
reversing\n");
display(node);
getch();
p=reverse(node);
printf("\n List after
reversing");
display(p);
getch();
}
void
create_link(struct link *node)
{
char ans;
i=0;
printf("\n Enter 'n' for
break:-");
ans=getchar();
while(ans!='n')
{
printf("\n Enter data
for node:-");
scanf("%d",&node->no);
node->next=(struct link
*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
fflush(stdin);
printf("\n Enter 'n' for
break:-");
ans=getchar();
i++;
}
printf("\n Total number of nodes : %d ", i);
}
void
display(struct link *node)
{
while(node)
{
printf("\n %d %u
" ,node->no,node);
node=node->next;
}
}
struct
link *reverse(struct link *node)
{
current=node;
pre=NULL;
while(current->next)
{
counter=(struct link
*)malloc(sizeof(struct link));
counter=current->next;
current->next=pre;
pre=current;
current=counter;
}
node=pre;
return(node);
}
No comments:
Post a Comment