Skip to content

Commit 8c73b58

Browse files
authored
Sort a stack.cpp
1 parent 3f0ed99 commit 8c73b58

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

LeetCode/Sort a stack.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
class SortedStack{
5+
public:
6+
stack<int> s;
7+
void sort();
8+
};
9+
10+
void printStack(stack<int> s)
11+
{
12+
while (!s.empty())
13+
{
14+
printf("%d ", s.top());
15+
s.pop();
16+
}
17+
printf("\n");
18+
}
19+
20+
int main()
21+
{
22+
int t;
23+
cin>>t;
24+
while(t--)
25+
{
26+
SortedStack *ss = new SortedStack();
27+
int n;
28+
cin>>n;
29+
for(int i=0;i<n;i++)
30+
{
31+
int k;
32+
cin>>k;
33+
ss->s.push(k);
34+
}
35+
ss->sort();
36+
printStack(ss->s);
37+
}
38+
}// } Driver Code Ends
39+
40+
41+
/*The structure of the class is
42+
class SortedStack{
43+
public:
44+
stack<int> s;
45+
void sort();
46+
};
47+
*/
48+
49+
/* The below method sorts the stack s
50+
you are required to complete the below method */
51+
void SortedStack :: sort()
52+
{
53+
//Your code here
54+
stack<int> temp;
55+
56+
while(!s.empty())
57+
{
58+
int x=s.top();
59+
s.pop();
60+
while( !temp.empty() && temp.top()<x)
61+
{
62+
s.push(temp.top());
63+
temp.pop();
64+
}
65+
temp.push(x);
66+
}
67+
while(!temp.empty())
68+
{
69+
s.push(temp.top());
70+
temp.pop();
71+
}
72+
73+
}

0 commit comments

Comments
 (0)