class StackOfPlates {
public:
StackOfPlates(int cap) {
}
void push(int val) {
}
int pop() {
}
int popAt(int index) {
}
};
/**
* Your StackOfPlates object will be instantiated and called as such:
* StackOfPlates* obj = new StackOfPlates(cap);
* obj->push(val);
* int param_2 = obj->pop();
* int param_3 = obj->popAt(index);
*/
class StackOfPlates:
def __init__(self, cap: int):
self.cap = cap
self.fullstack = [[]]
def push(self, val: int) -> None:
if self.cap <= 0:
# 如果初始容量小于0 直接return
return
if len(self.fullstack)==0 or len(self.fullstack[-1]) == self.cap:
# 当栈满了,或没有栈了,则新建一个栈
self.fullstack.append([])
self.fullstack[-1].append(val)
def pop(self) -> int:
if not self.fullstack or not self.fullstack[-1]:
return -1
ans = self.fullstack[-1].pop(-1)
if len(self.fullstack[-1]) == 0:
# 如果pop后栈为空,则删除该栈
self.fullstack.pop(-1)
return ans
def popAt(self, index: int) -> int:
if index >= len(self.fullstack) or not self.fullstack[index]:
return -1
popitem = self.fullstack[index].pop(-1)
if len(self.fullstack[index]) == 0:
self.fullstack.pop(index)
return popitem
# Your StackOfPlates object will be instantiated and called as such:
# obj = StackOfPlates(cap)
# obj.push(val)
# param_2 = obj.pop()
# param_3 = obj.popAt(index)
class StackOfPlates:
def __init__(self, cap: int):
self.cap = cap
self.array = []
def push(self, val: int) -> None:
# 处理边界情况:cap == 0 不让push
if self.cap == 0:
return
if not self.array or len(self.array[-1]) >= self.cap:
self.array.append([val])
else:
self.array[-1].append(val)
def pop(self) -> int:
val = -1
if self.array and self.array[-1]:
val = self.array[-1].pop()
if not self.array[-1]: self.array.pop()
return val
def popAt(self, index: int) -> int:
val = -1
if len(self.array) >= index + 1:
val = self.array[index].pop()
if not self.array[index]: self.array.pop(index)
return val
# Your StackOfPlates object will be instantiated and called as such:
# obj = StackOfPlates(cap)
# obj.push(val)
# param_2 = obj.pop()
# param_3 = obj.popAt(index)
class StackOfPlates {
private:
vector<stack<int>> stacks;
int capacity;
public:
StackOfPlates(int cap) : capacity(cap) {}
void push(int val) {
if (capacity > 0) {
if (stacks.empty() or static_cast<int>(stacks.back().size()) >= capacity)
stacks.emplace_back();
stacks.back().emplace(val);
}
}
int pop() {
return popAt(static_cast<int>(stacks.size()) - 1);
}
int popAt(int index) {
int res = -1;
if (index >= 0 and index < static_cast<int>(stacks.size())) {
res = stacks[index].top();
stacks[index].pop();
if (stacks[index].empty())
stacks.erase(next(stacks.begin(), index));
}
return res;
}
};
/**
* Your StackOfPlates object will be instantiated and called as such:
* StackOfPlates* obj = new StackOfPlates(cap);
* obj->push(val);
* int param_2 = obj->pop();
* int param_3 = obj->popAt(index);
*/