class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
private int size;
/** Initialize your data structure here. */
public MyStack() {
this.queue1 = new LinkedList<Integer>();
this.queue2 = new LinkedList<Integer>();
this.size = 0;
}
/** Push element x onto stack. */
public void push(int x) {
if(queue1.peek() != null){
queue1.offer(x);
}else if(queue2.peek() != null){
queue2.offer(x);
}else{
//都为空,则用queue1开始
queue1.offer(x);
}
size++;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(empty()){
throw new RuntimeException("无数据");
}
int e = 0;
if(queue2.peek() != null){
for(int i = 0; i < size - 1; i++){
queue1.offer(queue2.poll());
}
e = queue2.poll();
}else{
for(int i = 0; i < size - 1; i++){
queue2.offer(queue1.poll());
}
e = queue1.poll();
}
this.size--;
return e;
}
/** Get the top element. */
public int top() {
if(empty()){
throw new RuntimeException("无数据");
}
int e = 0;
if(queue2.peek() != null){
for(int i = 0; i < size; i++){
e = queue2.poll();
queue1.offer(e);
}
}else{
for(int i = 0; i < size; i++){
e = queue1.poll();
queue2.offer(e);
}
}
return e;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return size == 0;
}
public int size(){
return this.size;
}
}
栈实现队列:
class MyQueue {
Stack <Integer> stack = new Stack<Integer>();
Stack <Integer> stackTemp = new Stack<Integer>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stackTemp.empty()) {
while(!stack.empty()){
stackTemp.push(stack.pop());
}
}
int temp = 0;
if(!stackTemp.empty()) {
temp = stackTemp.pop();
}
/*
while(!stackTemp.isEmpty()){
stack.push(stackTemp.pop());
}*/
return temp;
}
/** Get the front element. */
public int peek() {
while(!stack.empty()){
stackTemp.push(stack.pop());
}
int temp = stackTemp.peek();
while(!stackTemp.empty()){
stack.push(stackTemp.pop());
}
return temp;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackTemp.empty() && stack.empty();
}
}
最小栈:
class MinStack {
/** initialize your data structure here. */
public MinStack() {
}
Stack <Integer> stack = new Stack<Integer>();
Stack <Integer> minstack = new Stack<Integer>();
//int[] stack = new int[40];
int i = 0;
///int[] minstack = new int[40];
int j = 0;
//入栈 对两个栈都要入栈
//每次放入之前需要看最小栈
//的栈顶元素的值比较
public void push(int x) {
stack.push(x);
if(minstack.empty()){
minstack.push(x);
}else{
if(x <= minstack.peek()){
//维持最小栈的最小值,也是栈的最小值
minstack.push(x);
}
}
}
//出栈不是出最小栈
public void pop() {
if(!stack.empty()){
int element = stack.pop();
if(element == minstack.peek()){
minstack.pop();
}
}
}
//返回栈顶元素
public int top() {
if(stack.empty()){
return -1;
}
else{
return stack.peek();
}
}
//返回栈最小元素
public int getMin() {
return minstack.peek();
}
}