This problem can be solved in complexity o (n ^ 2). This can be done without using the largest pop-up and keeping the rest elements in the second stack and updating the size of the first stack, and then dropping back to the first stack. look at the code snippet.
#include<stdio.h> func(struct stack *s1) { struct stack* s2=(struct stack*) malloc(sizeof(struct stack)) int i=0; int max=INT_MIN; size=s1->size; if(s1->size==0) { return; } for(;i<size;i++) { while(size(s1)!=size)//popping the elements and pushing in s2 stack and keeping track of maximum element. { temp=pop(s1); if(temp>max) { push(s2,max); max=temp; } } push(s1,max);//pushing the max element into stack s1 back and updating the size in push operation. while(!empty(s2))//pushing extracted numbers back into stack s1 from s2. { push(s1,pop(s2)); } } }
user4763576
source share