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();

    }

    }

  • 相关阅读:
    唐-诗:《旅夜书怀》
    唐-诗:《蜀相》
    唐-诗:《绝句四首》
    唐-诗:《望庐山瀑布》
    唐-诗-七言绝句:《黄鹤楼送孟浩然之广陵》
    汉-诗歌:《大风歌》
    makefile中的一点知识
    我们该不该“越级汇报”
    SDUT--找朋友(BFS&amp;&amp;DFS)
    智能社区--HI3516C可视门禁研发出来咯
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12420516.html
Copyright © 2011-2022 走看看