《剑指offer》-用两个栈来实现一个队列

import java.util.Stack;
/*
 *用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 *思路:两次先进后出变成先进先出(画图)
 */
public class UseStackImplementQueue {
	Stack stack1 = new Stack();
    Stack stack2 = new Stack();
    
    public void push(int node) {
    	stack1.push(node);
    }
    
    public int pop() {
    	if(stack1.isEmpty() || !(stack2.isEmpty())) {
    		return -1;
    	}
    	
    	while(!stack1.isEmpty()) {
    		stack2.push(stack1.pop());
    	}
    	
    	int value = stack2.pop();
    	while(!stack2.isEmpty()) {	//恢复现场:始终保持栈1里存元素,栈2里不存元素。
    		stack1.push(stack2.pop());
    	}
        
    	return value;
    }
    
    public static void main(String[] args) {
		UseStackImplementQueue t = new UseStackImplementQueue();
		t.push(1);
		t.push(2);
		t.push(3);
		System.out.println(t.pop());
		t.push(4);
		System.out.println(t.pop());
	}
}

你可能感兴趣的:(剑指offer)