利用两个栈实现队列的入队出队

这里写图片描述

import java.util.ArrayList;
import java.util.Stack;

/**
@author:micro_hz
2015年8月18日
 */
public class Quen {
    //初始化两个栈
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    //第二个栈计数,入第二个栈时候需要用
    int num = 0;
    public void push(int node) {
        stack1.add(node);
        num ++;
        //若第二只有一个
        if(num == 1)
        {
            stack2.add(stack1.pop());
        }
        if(num > 1)
        {
            ArrayList<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < num - 1; i++) {
                list.add(stack2.pop());
            }
            stack2.add(stack1.pop());
            for (int i = list.size() - 1; i >= 0; i --) {
                stack2.push(list.get(i));
            }
        }
    }

    public int pop() {
        num --;
        return stack2.pop();
    }
}

方法2:

import java.util.ArrayList;
import java.util.Stack;

/**
@author:micro_hz
2015年8月18日
 */
public class Quen {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    int num = 0;
    public void push(int node) {
        stack1.add(node);

        if(num == 0)
        {
            stack2.add(stack1.pop());
            num ++;
        }
        else 
        {
            ArrayList<Integer> list = new ArrayList<Integer>();
            while(!stack2.isEmpty())
            {
                list.add(stack2.pop());
            }
            stack2.add(stack1.pop());
            num ++;
            for (int i = list.size() - 1; i >= 0; i --) {
                stack2.push(list.get(i));
            }
        }
    }

    public int pop() {
        num --;
        return stack2.pop();
    }
}

不利用集合:

import java.util.Stack;
public class Solution {

   Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
   public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if(!stack2.isEmpty())
        {
            return stack2.pop();
        }
        while(!stack1.isEmpty())
        {
            stack2.push(stack1.pop());
        }

        return stack2.pop();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值