-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortStacks.java
More file actions
54 lines (41 loc) · 1.27 KB
/
SortStacks.java
File metadata and controls
54 lines (41 loc) · 1.27 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
54
package com.company;
import java.util.*;
public class SortStacks {
public static Stack<Integer> sortStack(Stack<Integer> stack){
Stack<Integer> temp = new Stack<Integer>();
temp.push(stack.pop());
int current;
while(!stack.empty()){
current = stack.pop();
if(current < temp.peek()){
while(!temp.empty()){
stack.push(temp.pop());
}
temp.push(current);
}
else{
temp.push(current);
}
}
while(!temp.empty()){
stack.push(temp.pop());
}
return stack;
}
public static void main(String[] args){
Stack<Integer> stack = new Stack<Integer>();
Random random = new Random();
for(int i = 0; i < 10; i++){
stack.push(random.nextInt(10) + 1);
System.out.print(stack.peek() + " ");
}
// System.out.println(stack.size());
System.out.println();
Stack<Integer> sortedStack = sortStack(stack);
// System.out.println(sortedStack.size());
// System.out.println(stack.size());
while(!sortedStack.empty()){
System.out.print(sortedStack.pop() + " ");
}
}
}