用数组结构实现大小固定的队列和栈
用数组结构实现大小固定的队列和栈
1. 队列
可以通过 start 和 end两个指针来控制队列的进出,通过设置size来简化判断队列状态。需要注意 nextIndex 方法,指针可以循环的在数组中跑起来,不许要担心数组指针位置问题。
class ArrayQueue {
private static int size;
private static int start;
private static int end;
private static int[] nums;
public ArrayQueue(int length) {
this.nums = new int[length];
}
public int get() {
if (!isEmpty()){
size--;
int num = nums[start];
start=nextIndex(start);
return num;
}else{
return -1;
}
}
public void put(int element) {
if (!isFull()) {
nums[end] = element;
end = nextIndex(end);
size++;
}
}
public boolean isFull() {
if (size == nums.length) {
System.out.println("QUEUE IS FULL");
return true;
} else {
return false;
}
}
public boolean isEmpty() {
if (size == 0) {
System.out.println("QUEUE IS EMPTY");
return true;
} else {
return false;
}
}
private int nextIndex(int index){
if (index == nums.length-1){
return 0;
}else{
return ++index;
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("start\t");
int key = start;
for (int i=0;i<size;i++){
stringBuilder.append(nums[key]+"\t");
key = nextIndex(key);
}
stringBuilder.append("end\t");
return stringBuilder.toString();
}
}
2. 栈
利用一个指针就可以是实现栈的压入和弹出。
class ArrayStack{
static int size = 0 ;
static int[] array ;
static int point = 0;
public ArrayStack(int lengh) {
this.array = new int[lengh];
}
public static int peek(){
if (isEmpty()){
return -1;
}
return array[point-1];
}
public static int pop(){
if (isEmpty()){
return -1;
}
size--;
return array[--point];
}
public static void push(int element){
if (isFull()){
return;
}
array[point++] = element;
size++;
}
public static boolean isEmpty(){
return size==0;
}
public static boolean isFull(){
if (size==array.length){
System.out.println("Stack is full");
return true;
}else{
return false;
}
}
public String toString(){
StringBuilder builder = new StringBuilder("[");
for (int i=0;i<size;i++){
builder.append(array[i]+"\t");
}
builder.append("]");
return builder.toString();
}
}