Skip to content

Latest commit

 

History

History
36 lines (28 loc) · 779 Bytes

两个栈实现队列.md

File metadata and controls

36 lines (28 loc) · 779 Bytes

####两个栈实现队列

用两个栈实现队列,支持在头部删除元素,和在尾部添加元素。


	package lintcode;
	
	import java.util.Stack;

	public class QueueWithStack {
	    Stack stack1 = new Stack<>();
	    Stack stack2 = new Stack<>();

	    public void appendTail(T val) {
	        if (!stack2.empty()) {
	            while (!stack2.empty()) {
	                stack1.push(stack2.pop());
	            }
	        }
	
	        stack1.push(val);
	    }

	    public T deleteHead() {
	        if (!stack1.empty()) {
	            while (!stack1.empty()) {
	                stack2.push(stack1.pop());
	            }
	        }
	
	        if (stack2.empty()) {
	            return null;
	        }
	
	        return stack2.pop();
	    }
}