【剑指offer】五,二个栈实现队列

it2022-05-05  145

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 分析:栈是后进先出的数据结构,队列是先进先出的数据结构。用两个栈来模拟一个队列,可以考虑使用一个栈s1作为入队操作的栈,一个栈S2作为中介来实现出队操作,来实现队列的操作。可能面临的情况有四种(1)栈1为空,栈2不空 (2)栈1为空,栈2也为空 (3)栈1不空,栈2为空(4)栈1不空,栈2也不空。队四种情况进行分析处理。代码如下: 1 import java.util.Stack; 2 3 public class Solution { 4 Stack<Integer> stack1 = new Stack<Integer>(); 5 Stack<Integer> stack2 = new Stack<Integer>(); 6 7 public void push(int node) { 8 stack1.push(node); 9 } 10 11 public int pop() { 12 if(stack1.empty()&&stack2.empty()){ 13 return -1 ; 14 } 15 16 if(!stack1.empty()&&stack2.empty()){ 17 while(!stack1.empty()){ 18 int temp = stack1.pop() ; 19 stack2.push(temp) ; 20 } 21 } 22 23 return stack2.pop() ; 24 25 26 27 } 28 }

大家如有更好的方法,欢迎留言指教。

转载于:https://www.cnblogs.com/huntertoung/p/4756220.html


最新回复(0)