天天看點

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 }