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

    }

    }

  • 相关阅读:
    组件GIS 0 前言
    GIS数据结构与算法
    GIS数据结构与算法 0 前言
    Git推送本地工程到远程仓库
    为知笔记+Typora+PicGo发表博客园博客
    时间记录"时间块"的使用技巧
    WebGIS学习路线
    [c++指针教程]用简单链表练习指针
    动态规划题目整理
    图论刷题整理
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12420516.html
Copyright © 2011-2022 走看看