简单数组转栈和队列

xiaoxiao2025-06-08  17

数组转栈

对于数组转栈,首先要定义一个标记指针指针index指向栈的栈底,也就是数组的首部。根据栈的原理,压栈一次index+1.当压栈的数量等于数组长度,报错溢出。

代码如下:

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

 

数组转队列

对于数组转队列不能简单的直接进队列和出队列。需要把队列的首部和尾部做好标记,当需要进(出)队列的时候可以直接操作。定义start和end指向队列的首部(数组的首部)。定义一个size,用来统计队列里元素的个数。当元素个数等于数组长度,报错溢出。

代码如下:

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

 

转载请注明原文地址: https://www.6miu.com/read-5031502.html

最新回复(0)