Skip to content

Commit ff6d341

Browse files
committed
Sort a stack
1 parent 55c0d81 commit ff6d341

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

DSA Crack Sheet/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
- [Evaluation of Postfix Expression](https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1# "view question") - [Cpp Solution](./solutions/Evaluation%20of%20Postfix%20Expression.cpp)
155155
- [Inserting at the end of stack](https://stackoverflow.com/questions/45130465/inserting-at-the-end-of-stack "view topic")
156156
- [Reverse a stack using recursion](https://www.geeksforgeeks.org/reverse-a-stack-using-recursion/ "view topic")
157+
- [Sort a stack](https://practice.geeksforgeeks.org/problems/sort-a-stack/1# "view question") - [Cpp Solution](./solutions/Sort%20a%20stack.cpp)
157158
- []( "view question") - [Cpp Solution](./solutions/.cpp)
158159

159160
### Heap
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Sort a stack
3+
============
4+
5+
Given a stack, the task is to sort it such that the top of the stack has the greatest element.
6+
7+
Example 1:
8+
Input:
9+
Stack: 3 2 1
10+
Output: 3 2 1
11+
12+
Example 2:
13+
Input:
14+
Stack: 11 2 32 3 41
15+
Output: 41 32 11 3 2
16+
Your Task:
17+
You don't have to read input or print anything. Your task is to complete the function sort() which sorts the elements present in the given stack. (The sorted stack is printed by the driver's code by popping the elements of the stack.)
18+
19+
Expected Time Complexity : O(N*N)
20+
Expected Auixilliary Space : O(N) recursive.
21+
22+
Constraints:
23+
1<=N<=100
24+
25+
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
26+
*/
27+
28+
void insert(stack<int> &s, int t)
29+
{
30+
if (s.size() == 0 || s.top() < t)
31+
s.push(t);
32+
else
33+
{
34+
int temp = s.top();
35+
s.pop();
36+
insert(s, t);
37+
s.push(temp);
38+
}
39+
}
40+
41+
void SortedStack ::sort()
42+
{
43+
if (s.size() > 0)
44+
{
45+
int temp = s.top();
46+
s.pop();
47+
sort();
48+
insert(s, temp);
49+
}
50+
}

0 commit comments

Comments
 (0)