Skip to main content

SORT A STACK USING RECURSIONS

CODING:
#include<stdio.h>
#include<conio.h>
struct stack
{
int no;
struct stack *next;
};
struct stack *top=NULL;
struct stack *push(struct stack *);
struct stack *display(struct stack *);
void   sort(struct stack *);
void main()
{
clrscr();
top=push(top);
sort(top);
top=display(top);
getch();
}
struct stack *push(struct stack *top)
{
struct stack *new_stack;
int n,i;
printf("HOW TO STORE ELEMENT IN THE STACK:");
scanf("%d",&i);
while(0<i)
{
printf("ENTER THE NUMBER:");
scanf("%d",&n);
new_stack=(struct stack*)malloc(sizeof(struct stack*));
new_stack->no=n;
 if(top==NULL)
  {
   new_stack->next=NULL;
   top=new_stack;
   i--;
  }
 else
  {
   new_stack->next=top;
   top=new_stack;
   i--;
  }
}
return top;
}
struct stack *display(struct stack *top)
{
struct stack *new_stack;
new_stack=top;
printf("STACK");
while(new_stack!=NULL)
{
  printf("\n%d",new_stack->no);
  new_stack=new_stack->next;
}
return top;
}
void sort(struct stack *top)
{
struct stack *s;
int temp=0;
s=top;
while(s->next!=NULL && top->next!=NULL)
 {
  s=s->next;
  if(top->no>s->no)
   {
    temp=top->no;
    top->no=s->no;
    s->no=temp;
   }
 }
 if(top!=NULL)
  {
  top=top->next;
  sort(top);
  }
}

Comments