zoukankan      html  css  js  c++  java
  • java 数组实现队列和栈

    一、数组实现队列

     1 public class ArrayAsQueue {
     2     public static int head = 0;    //头指针
     3     public static int tail = 0;    //尾指针
     4     public static int count = 0;    //记录队列长度
     5     public static int[] array = new int[10];    //数组长度为10
     6 
     7     public static int offer(int num) {
     8         if (count == 10)
     9             return -1;
    10         array[tail] = num;
    11         tail = ++tail % 10;    //数组达到最后位置时,对其取模
    12         count++;
    13         return 1;
    14     }
    15 
    16     public static int poll() {
    17         if (count == 0)
    18             throw new RuntimeException();    //队列为空,抛出异常
    19         int tmp = array[head];
    20         head = ++head % 10;
    21         count--;
    22         return tmp;
    23     }
    24 }

    二、数组实现栈

     1 public class ArrayAsStack {
     2     public static int index = -1;
     3     public static int[] array = new int[10];
     4 
     5     public static int push(int num) {
     6         if (index  < 9) {
     7             index++;
     8             array[index] = num;
     9             return 1;
    10         }
    11         return -1;
    12     }
    13 
    14     public static int pop() {
    15         if (index == -1)
    16             throw new RuntimeException();
    17         else {
    18             int tmp = array[index];
    19             index--;
    20             return tmp;
    21         }
    22     }
    23 }
  • 相关阅读:
    Hive2.0函数大全(中文版)
    Centos7 安装并配置redis
    Java内部类
    beeline: 新版连接Hive server的工具
    jsoup的Document类
    Jsoup类
    jsoup的Node类
    jsoup的Element类
    Java中的多线程
    Java中的文件IO流
  • 原文地址:https://www.cnblogs.com/javaXRG/p/11580741.html
Copyright © 2011-2022 走看看