zoukankan      html  css  js  c++  java
  • 剑指offer(Java版)第七题:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead, 分别完成在队列尾部插入结点和在队列头部删除结点的功能。

    /*
    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,
    分别完成在队列尾部插入结点和在队列头部删除结点的功能。
    */

    import java.util.*;

    public class Class8 {
    static class stackToQueue{
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

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

    public int deleteHead(){
    if(stack2.empty()){
    if(stack1.empty()){
    throw new RuntimeException("队列为空!");
    }
    else{
    while(!stack1.empty()){
    stack2.push(stack1.pop());
    }
    }
    }
    if(stack2.empty()){
    if(stack1.empty()){
    if(stack1.empty()){
    throw new RuntimeException("队列操作存在错误!");
    }
    else{
    while(!stack1.empty()){
    stack2.push(stack1.pop());
    }
    }
    }
    }
    return stack2.pop();
    }
    }
    public void test() {
    stackToQueue stq= new stackToQueue();
    stq.appendTail(1);
    stq.appendTail(2);
    System.out.println(stq.deleteHead());
    stq.appendTail(3);
    System.out.println(stq.deleteHead());
    System.out.println(stq.deleteHead());
    }


    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Class8 c = new Class8();
    c.test();

    }

    }

  • 相关阅读:
    Alpha阶段项目复审
    复审与事后分析
    测试与发布(Alpha版本)
    第七天
    第六天
    团队作业第4周——项目冲刺
    第一天
    第二天
    第四天
    第五天
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12420516.html
Copyright © 2011-2022 走看看