剑指offer面试题9:用两个栈实现队列(Java 实现)

题目:用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。 队列中的元素为 int 类型。

思路:

首先定义两个栈 stack1 和 stack2 ,stack1 用来实现队列的 push 功能 ,stack2 用来缓冲实现队列的 pop 功能。

测试用例:

  1. 功能测试:分别往空和非空的队列中添加和删除元素。
  2. 边界测试:连续删除元素直至队列为空。
public class test_night {
	Stack<Integer> stack1 = new Stack<>();
	Stack<Integer> stack2 = new Stack<>();
	
	public void push(int node){
		stack1.push(node);
	}
	
	public int pop() throws Exception{
		if(stack1.isEmpty() && stack2.isEmpty()){
			throw new Exception("栈为空");
		}
		
		if(!stack1.isEmpty() && stack2.isEmpty()){
			stack2.push(stack1.pop());
		}
		return stack2.pop();
	}
}

相关题目:用两个队列实现一个栈。

//用两个队列实现一个栈
public class test_night1 {
	Queue<Integer> queue1 = new ArrayDeque<Integer>();
	Queue<Integer> queue2 = new ArrayDeque<Integer>();
	
	public void push(int node){
		//如果两个队列都为空,优先考虑把元素加入队列1
		if(queue1.isEmpty() && queue2.isEmpty()){
			queue1.add(node);
		}
		
		//哪个队列有元素就把元素加入队列所在元素的后面
		if(queue1.isEmpty()){
			queue2.add(node);
		}
		if(queue2.isEmpty()){
			queue1.add(node);
		}
	}
	
	public int pop() throws Exception{
		//如果两个栈都为空,则没有元素可以弹出,异常
		if(queue1.isEmpty() && queue2.isEmpty()){
			throw new Exception("队列为空");
		}
		//如果queue1中没有元素,queue2中有元素,将其queue2中的元素依次放入queue1中,直到最后一个元素,弹出即可
		if(queue1.isEmpty()){
			while(queue2.size()>1){
				queue1.add(queue2.poll());
			}
			return queue2.poll();
		}
		//如果queue2中没有元素,queue1中有元素,将其queue1中的元素依次放入queue2中,直到最后一个元素,弹出即可
		if(queue2.isEmpty()){
			while(queue1.size()>1){
				queue2.add(queue1.poll());
			}
			return queue1.poll();
		}
		return 1;
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_41163113/article/details/85849444