首页 > 其他 > 详细

剑指offer5:用两个栈实现队列

时间:2018-03-09 17:33:23      阅读:139      评论:0      收藏:0      [点我收藏+]

题目描述:

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

思路:

基本操作,栈是后进先出,队列是先进先出,两个栈正好反反得正

 1 import java.util.Stack;
 2 public class Lianggezhanduilie {
 3     Stack<Integer> stack1 = new Stack<Integer>();
 4     Stack<Integer> stack2 = new Stack<Integer>();
 5        
 6     public void push(int node) {
 7        stack1.push(node);
 8     }
 9        
10     public int pop() {
11         while(stack2.isEmpty()){
12             while(!stack1.isEmpty()){
13                 stack2.push(stack1.pop());    
14             }
15         }
16         int ans = stack2.pop();
17     return ans;
18        
19     }
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22 
23     }
24 
25 }

 

剑指offer5:用两个栈实现队列

原文:https://www.cnblogs.com/zlz099/p/8534675.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!