/** Initialize your data structure here. */ publicMyStack(){ queue = new LinkedList<>(); }
/** Push element x onto stack. */ //每次将插入的数据重新插入 publicvoidpush(int x){ queue.add(x); int size = queue.size(); while (size-->1){ queue.add(queue.poll()); } }
/** Removes the element on top of the stack and returns that element. */ publicintpop(){ return queue.poll(); }
/** Get the top element. */ publicinttop(){ return queue.peek(); }
/** Returns whether the stack is empty. */ publicbooleanempty(){ return queue.isEmpty(); }
}
3. 最小值栈
155
按照上面的思路,我们只需要设计一个数据结构,使得每个元素 a 与其相应的最小值 m 时刻保持一一对应。因此我们可以使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。