剑指09:两个栈实现队列

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

栈:Stack类

这是java.util.Stack包下的类,因此可以拿来即用。

常用非静态方法

Stack stack1 = new Stack();
stack1.push(1);//入栈
Integer i = stack1.peek();//取值但不出栈
Integer i = stack1.pop();//出栈且出值

1.第一个版本

两个stack:入队列时,直接appendTail到stack1栈中
而出队列时,先把stack1栈中的元素出栈,然后再stack2中入栈
这样stack2下次pop出来的就是stack1中的head
从而达到了队列的效果

public class CQueue {

  private Stack<Integer> stack1;
  private Stack<Integer> stack2;

  public static void main(String[] args) {
    CQueue cQueue = new CQueue();
    cQueue.appendTail(1);
    cQueue.appendTail(2);
    cQueue.appendTail(3);
    System.out.println(cQueue.deleteHead());//打乱顺序
    cQueue.appendTail(4);

    System.out.println(cQueue.deleteHead());
    System.out.println(cQueue.deleteHead());
    System.out.println(cQueue.deleteHead());

  }

  public CQueue() {
    this.stack1 = new Stack<Integer>();
    this.stack2 = new Stack<Integer>();
  }

  public void appendTail(int value) {//队列尾增
  
    while(!stack2.isEmpty()){
      stack1.push(stack2.pop());
    }
    stack1.push(value);
  }

  public int deleteHead() {//队列头出
  if(stack1.isEmpty() && stack2.isEmpty()){
	return -1;
	}
    while(!stack1.isEmpty()){
      stack2.push(stack1.pop());
    }
    return stack2.pop();
  }
}

2.第二个版本

stack2如果不为空,那么下一个pop的就是head
如果stack2为空,那么则把stack1中的元素拿过来,再pop

  public static void main(String[] args) {
    CQueue cQueue = new CQueue();
    cQueue.appendTail(1);
    cQueue.appendTail(2);
    cQueue.appendTail(3);
    System.out.println(cQueue.deleteHead());
    cQueue.appendTail(4);

    System.out.println(cQueue.deleteHead());
    System.out.println(cQueue.deleteHead());
    System.out.println(cQueue.deleteHead());

  }

  public CQueue() {
    this.stack1 = new Stack<Integer>();
    this.stack2 = new Stack<Integer>();
  }

  public void appendTail(int value) {
    stack1.push(value);
  }

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

3.也可以用ArrayList代替Stack

来自力扣

class CQueue {
    LinkedList<Integer> A, B;
    public CQueue() {
        A = new LinkedList<Integer>();
        B = new LinkedList<Integer>();
    }
    public void appendTail(int value) {
        A.addLast(value);
    }
    public int deleteHead() {
        if(!B.isEmpty()) return B.removeLast();
        if(A.isEmpty()) return -1;
        while(!A.isEmpty())
            B.addLast(A.removeLast());
        return B.removeLast();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值