java 数组实现队列和栈
发布时间:2020-12-15 07:39:16 所属栏目: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
一、数组实现队列 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |