* 栈和队列实现:
* 1.双向链表实现
* 2.数组实现
*
* 基于数组实现
public class StackOrQueueBaseOnArray {
/**
* 数组实现栈:
* 1.只要满了报异常
* 2.没满保证正确性
*/
public static class ArrayStack{
private int index;
private final int[] arr;
private static final int INIT_CAPACITY = 10;
public ArrayStack(){
this(INIT_CAPACITY);
}
public ArrayStack(int capacity){
this.arr = new int[capacity];
}
public void push(int val){
if(index == arr.length){
System.out.println("this stack is full!");
return;
}
this.arr[index] = val;
this.index ++;
}
public int pop(){
if(index <= 0){
return -1;
}
index --;
return this.arr[index];
}
}
/**
* 数组实现队列:
* 1.可循循环利用现有的数组容量
* 2.确定一种机制实现循环可用的队列,类似: ring buffer
*/
public static class ArrayQueue{
private final int[] arr;
/*记录存入元素的下一个位置*/
private int pushIndex;
/*记录刚被取出的元素位置*/
private int popIndex;
/*有效数据容量*/
private int size;
private final int limit;
public ArrayQueue(int limit) {
this.arr = new int[limit];
this.pushIndex = 0;
this.popIndex = 0;
this.size = 0;
this.limit = limit;
}
public void push(int val){
if(size == limit){
throw new RuntimeException("队列已满");
}
size ++;
arr[pushIndex] = val;
pushIndex = nextIndex(pushIndex);
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("队列已空");
}
size --;
int res = arr[popIndex];
popIndex = nextIndex(popIndex);
return res;
}
public boolean isEmpty(){
return size == 0;
}
public boolean isFull(){
return size == limit;
}
/*index传入时已经读写了数据,只是改变下一次的索引*/
private int nextIndex(int index){
return index < limit - 1 ? index + 1 : 0;
}
}
}
左神算法学习