代码如下:
package com.栈队组; public class Array_To_Stack{ /* * 数组转为栈。 * 定义一个数组,定义一个指针index。 * 建立一个方法setSize(),用来定义栈的长度,且index=0; * 定义压栈方法push(int num),判断index的大小防止溢出,num进栈,index++ * 定义出栈方法pop(),判断index大小防止溢出,index指向的数出栈,index--; */ private static Integer arr [] ; private static Integer index ; public static void setSize(int initSize){ if(initSize<0){ throw new IllegalArgumentException("栈不能小于0!") ; } arr = new Integer[initSize] ; index = 0 ; } public static void push(int num){ if(index==arr.length){ throw new ArrayIndexOutOfBoundsException("栈已满!") ; } arr[index++] = num ; } public static Integer pop(){ if(index<0){ throw new ArrayIndexOutOfBoundsException("栈没有数据!") ; } return arr[--index] ; } public static void main(String[] args) { setSize(5); push(1); push(2); push(3); push(4); push(5); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); } }
代码如下:
package com.栈队组; public class Array_To_Queue { private static Integer arr[] ; private static Integer end ; private static Integer start ; private static Integer size ; public static void setSize(int initSize){ if(initSize<0){ throw new IllegalArgumentException("队列的大小不能小于 0") ; } arr = new Integer[initSize] ; size = 0; start = 0 ; end = 0; } public static void push(int num){ if(size == arr.length){ throw new ArrayIndexOutOfBoundsException("队列已满!") ; } size ++ ; start = start == arr.length - 1 ? 0 : start +1 ; arr[start] = num ; } public static Integer pop(){ if(size<0){ throw new ArrayIndexOutOfBoundsException("队列已空!"); } size -- ; int temp = end ; end = end == arr.length - 1 ? 0 : end +1 ; return arr[end] ; } public static void main(String[] args) { setSize(5); push(1); push(2); push(3); push(4); push(5); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); System.out.println(pop()); } }