-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortStack.java
More file actions
53 lines (42 loc) · 1.19 KB
/
SortStack.java
File metadata and controls
53 lines (42 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/************************************************************************
*
* Given a stack, the task is to sort it such that the top of the
* stack has the greatest element.
*
* Example 1:
*
* Input:
* Stack: 3 2 1
* Output: 3 2 1
* Example 2:
*
* Input:
* Stack: 11 2 32 3 41
* Output: 41 32 11 3 2
*
***************************************************************************/
import java.util.Stack;
public class SortStack {
public static void main(String[] args) {
SortStack sortStack = new SortStack();
Stack<Integer> integerStack = new Stack<>();
integerStack.push(10);
integerStack.push(3);
integerStack.push(7);
System.out.println(integerStack);
System.out.println(sortStack.sort(integerStack));
}
public Stack<Integer> sort(Stack<Integer> s) {
int[] integers = new int[s.size()];
int i = 0;
while (!s.isEmpty()) {
integers[i] = s.pop();
i++;
}
java.util.Arrays.sort(integers);
for (int j = 0; j < integers.length; j++) {
s.push(integers[j]);
}
return s;
}
}