c code to sort stack using stacks

  • cstack
  • write a c code to sort stack using stacks

    WAP to sort the elements inside a stack using only push and pop operation. Any number of additional stacks may be used.

    Code

    WAP to sort the elements inside a stack using only push and pop operation. Any number of additional stacks may be used. #include <stdio.h> #include <stdlib.h> struct stack { int size; int top; int *arr; }; int isEmpty(struct stack *ptr) { if (ptr->top == -1) { return 1; } else { return 0; } } int isFull(struct stack *ptr) { if (ptr->top == ptr->size - 1) { return 1; } else { return 0; } } void push(struct stack *ptr, int val) { if (isFull(ptr)) { printf("Stack Overflow! Cannot push %d to the stack\n", val); } else { ptr->top++; ptr->arr[ptr->top] = val; } } int pop(struct stack *ptr) { if (isEmpty(ptr)) { printf("Stack Underflow! Cannot pop from the stack\n"); return -1; } else { int val = ptr->arr[ptr->top]; ptr->top--; return val; } } int stack_top(struct stack *ptr) { return ptr->arr[ptr->top]; } struct stack *sort(struct stack *ptr, struct stack *ts) { while (!isEmpty(ptr)) { int tmp = stack_top(ptr); pop(ptr); while (!isEmpty(ts) && stack_top(ts) > tmp) { push(ptr, stack_top(ts)); pop(ts); } push(ts, tmp); } return ts; } void display(struct stack *ptr) { printf("elements : "); int k = ptr->top; while (k != -1) { printf("%d ", ptr->arr[k]); k--; } } int main() { int c, p; struct stack *sp = (struct stack *)malloc(sizeof(struct stack)); struct stack *ts = (struct stack *)malloc(sizeof(struct stack)); printf("enter the size of stack : "); scanf("%d", &p); sp->size = p; sp->top = -1; sp->arr = (int *)malloc(sp->size * sizeof(int)); ts->size = p; ts->top = -1; ts->arr = (int *)malloc(ts->size * sizeof(int)); printf("Stack has been created successfully\n"); push(sp, 11); push(sp, 5); push(sp, 8); push(sp, 10); push(sp, 12); push(sp, 7); display(sp); sp = sort(sp, ts); printf("\n"); display(sp); return 0; }