Sunday 31 July 2016

Sort a stack in ascending order using another stack.

#include <iostream>
#include<stack>
using namespace std;

int main() {
stack<int>s;
s.push(9);
s.push(59);
s.push(2);
s.push(1);
stack<int>s1;
s1.push(s.top());
s.pop();

while(!s.empty())
{
int v=s.top();
s.pop();

while(!s1.empty()&&s1.top()<v)
{
s.push(s1.top());
s1.pop();
}
s1.push(v);


}
s=s1;
while(!s.empty())
{
cout<<s.top()<<"  ";
s.pop();
}

return 0;
}

No comments:

Post a Comment