-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetOfStacks.java
More file actions
81 lines (72 loc) · 2.05 KB
/
SetOfStacks.java
File metadata and controls
81 lines (72 loc) · 2.05 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.company;
import java.util.*;
//Cracking the Coding Interview Question 3.3
public class SetOfStacks {
private ArrayList<Stack<Integer>> stacks = new ArrayList<>();
private int capacity;
private int currentPile = 0;
public SetOfStacks(int capacity){
this.capacity = capacity;
this.stacks.add(new Stack<Integer>());
}
public void push(int num){
if(stacks.get(currentPile).size() < capacity){
stacks.get(currentPile).push(num);
}
else{
currentPile++;
stacks.add(new Stack<Integer>());
stacks.get(currentPile).push(num);
}
}
public int pop(){
if(stacks.get(stacks.size()-1).size() == 0){
stacks.remove(stacks.size()-1);
currentPile--;
}
return stacks.get(currentPile).pop();
}
public int popAt(int pile){
//System.out.println(stacks.get(pile-1).size());
System.out.println(currentPile);
if(stacks.get(pile-1) != null){
int v = stacks.get(pile-1).pop();
if(stacks.get(pile-1).empty()){
stacks.remove(pile-1);
currentPile--;
}
return v;
}
else{
return -1;
}
}
public java.lang.Object peek(){
Stack pile = stacks.get(currentPile);
return pile.peek();
}
public static void main(String[] args){
SetOfStacks stacks = new SetOfStacks(5);
stacks.push(1);
stacks.push(2);
stacks.push(3);
stacks.push(4);
stacks.push(5);
stacks.push(1);
stacks.push(2);
stacks.push(3);
stacks.push(4);
stacks.push(5);
stacks.push(6);
stacks.push(8);
System.out.println(stacks.peek());
stacks.popAt(2);
System.out.println(stacks.peek());
stacks.popAt(2);
stacks.popAt(2);
stacks.popAt(2);
System.out.println(stacks.peek());
stacks.popAt(2);
System.out.println(stacks.peek());
}
}