用固定长度的数组实现stack queue

 1 package my_basic.class_3;
 2 
 3 /**
 4  * 用数组结构实现大小固定的队列和栈
 5  */
 6 public class Code_01_Array_stack_queue {
 7     
 8     public static class ArrayStack{
 9         private Integer[] arr;
10         private Integer size;
11         
12         public ArrayStack(int initSize) {
13             if (initSize < 0) {
14                 throw new IllegalArgumentException("The init size is less than 0");
15             }
16             arr = new Integer[initSize];
17             size=0;
18             
19         }
20         
21         public Integer peek() {
22             if (size == 0) {
23                 return null;
24             }
25             return arr[size-1];
26             
27         }
28         public void push(int num) {
29             if (size == arr.length) {
30                 throw new ArrayIndexOutOfBoundsException("the stack is full");
31             }
32             arr[size++] = num;
33         }
34         public Integer pop() {
35             if (size == 0) {
36                 throw new ArrayIndexOutOfBoundsException("the stack is empty");
37             }
38             size--;
39             return arr[size];
40         }
41     
42 }
43 
44     public static class ArrayQueue{
45         private Integer[] arr;
46         private int size;
47         private int first;
48         private int last;
49         
50         public ArrayQueue(int initSize) {
51             if (initSize < 0 ) {
52                 throw new IllegalArgumentException("The init size is less than 0");
53             }
54             arr = new Integer[initSize];
55             size=0;
56             first=0;
57             last=0;
58         }
59         public Integer peek() {
60             if (size == 0) {
61                 return null;
62             }
63             return arr[first];
64         }
65         public void push(int obj) {
66             if (size == arr.length) {
67                 throw new ArrayIndexOutOfBoundsException("the queue is full");
68             }
69             size++;
70             arr[last] = obj;
71             last = (last == arr.length-1) ? 0 : last++;
72         }
73         public Integer poll() {
74             if (size == 0) {
75                 throw new ArrayIndexOutOfBoundsException("the queue is empty");
76             }
77             size--;
78             int res = first;
79             first = (first == arr.length-1)? 0 : first++;
80             return arr[res];
81         }
82         
83     }
84     
85     public static void main(String[] args) {
86         
87         
88     }
89         
90     
91 }

 

转载于:https://www.cnblogs.com/lihuazhu/p/10834509.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值