数组实现栈:栈是一种后进先出的数据结构,用数组实现起来比较简单。
package lianxi03;
public class Code01_Array_Stcak {
public static void main(String[] args) {
ArrayStack s=new ArrayStack(2);
s.add(1);
s.add(2);
System.out.println(s.peek());
}
public static class ArrayStack{
private Integer[] arr;
private Integer size;
public ArrayStack(int initSize){
if(initSize<0)throw new IllegalArgumentException("The inti size is less than 0");
arr=new Integer[initSize];
size=0;
}
public void add(int num){
if(size>=arr.length)
throw new ArrayIndexOutOfBoundsException("The array is full");
arr[size++]=num;
}
public Integer pop(){
if(size==0)throw new ArrayIndexOutOfBoundsException("The array is empty");
return arr[--size];
}
public Integer peek(){
if(size==0)return null;
return arr[size-1];
}
}
}
数组实现堆:堆是一种先进先出的数据结构,用数组实现堆的过程中,除了要用一个size来记录数组的大小,还需要一个first来记录数组的开始位置,以及last来确定数组的末尾位置。
package lianxi03;
import java.lang.reflect.Array;
public class Code02_Array_Queue {
public static void main(String[] args) {
Array_Queue queue=new Array_Queue(3);
queue.add(1);
queue.add(2);
System.out.println(queue.peek());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
public static class Array_Queue{
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
public Array_Queue(int intiSize){
if(intiSize<0)throw new IllegalArgumentException("The inti is less than 0");
arr=new Integer[intiSize];
size=0;
first=0;
last=0;
}
public void add(int num){
if(size==arr.length)throw new ArrayIndexOutOfBoundsException("The array is full");
size++;
arr[last]=num;
last=last==arr.length-1?0:last+1;
}
public Integer peek(){
if(size==0)return null;
return arr[first];
}
public Integer pop(){
if(size==0)throw new ArrayIndexOutOfBoundsException("The array is empty");
size--;
int tmp=arr[first];
first=first==arr.length-1?0:first+1;
return tmp;
}
}
}