26-咸鱼学Java-两个栈实现队列

栈的代码详情

双栈队列代码

代码

/**
 * 双栈队列
 * @author 焦焱
 *
 */
public class TwoStackQueue {
private LinkStack t1 = new LinkStack();
private LinkStack t2 = new LinkStack();
private int size=0;


public int getSize() {
    return size;
}

/**
 * 入队
 * @param val 数据
 */
public void push(int val) {
    t2.push(val);
    size++;
}
/**
 * 出队
 * @return 数据
 */
public int pop() {
    if(isEmpty())
    {
        return -1;
    }
    int re = -1;
    //先将t2中的数据全部弹出压入t1
    while(!t2.isEmpty())
    {
        t1.push(t2.pop()    );
    }
    //t1弹出数据
    re = t1.pop();
    size--;
    //重新将t1的压入t2
    while(!t1.isEmpty())
    {
        t2.push(t1.pop());
    }
    return re;
}
/**
 * 获得队顶元素
 * @return 数据
 */
public int getTop() {
    //和队相同,只不过将pop改为getTop即可
    if(isEmpty())
    {
        return -1;
    }
    int re = -1;
    while(!t2.isEmpty())
    {
        t1.push(t2.pop());
    }
    re = t1.getTop();
    while(!t1.isEmpty())
    {
        t2.push(t1.pop());
    }
    return re;
}
/**
 * 显示所有数据
 */
public void show() {
    while(!t2.isEmpty())
    {
        t1.push(t2.pop());
    }
    while(!t1.isEmpty())
    {
        //这块注意不能pop要用getTop
        System.out.print(t1.getTop()+" ");
        t2.push(t1.pop());
    }
}
/**
 * 判断队是否为空
 * @return
 */
public boolean isEmpty() {
    return t2.isEmpty();
}
}

测试

public static void main(String[] args) {
    TwoStackQueue t = new TwoStackQueue();
    for (int i = 0; i < 10; i++) {
        t.push(i);
    }
    t.show();
    System.out.println(t.isEmpty());
    for (int i = 0; i < 10; i++) {
        System.out.print(t.pop() +" ");
    }

结果
0 1 2 3 4 5 6 7 8 9 false
0 1 2 3 4 5 6 7 8 9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值