栈和队列相关总结。
1.用数组结构实现大小固定的栈
首先,用数组实现固定大小的栈,维护一个size指针,指向数组中待插入值的位置,size指向0说明是空的,size指向arr.length说明越界,数组已经满了。
java参考代码如下:
package chapter2;
public class P68_ArrayStack {
private int[] arr;
private int size;
public P68_ArrayStack(int length){
if(length<0){
throw new IllegalArgumentException("The init size is less than 0");
}
arr=new int[length];
size=0;
}
public void push(int val){
if(size==arr.length){
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
arr[size++]=val;
}
public int pop(){
if(size==0){
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
return arr[--size];
}
public int peek(){
if(size==0){
return -1;//equals null
}
return arr[size-1];
}
public static void main(String[] args) {
P68_ArrayStack stack=new P68_ArrayStack(4);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.peek());//null
}
}
2.用数组结构实现大小固定的队列
队列需要两头进行操作,我们用两个指针first和last分别指向数据的第一个和最后一个数据的后一个位置,size仍然是代表数组中数据的个数,插入和删除都要相应的加减size。与栈不同的是,当first或last到了数组的最后一个位置,只要size不为0,仍然要
java参考代码如下:
package chapter2;
public class P68_ArrayQueue {
private Integer[] arr;
private int size;
private int first;
private int last;
public P68_ArrayQueue(int length){
this.arr=new Integer[length];
this.size=0;
this.first=0;
this.last=0;
}
public void push(int val){
if(size==arr.length){
throw new IllegalArgumentException("the queue is full!");
}
size++;
arr[last]=val;
last=last==arr.length-1?0:last+1;
}
public int pop(){
if(size==0){
throw new IllegalArgumentException("the queue is empty!");
}
size--;
int temp=first;
first=first==arr.length-1?0:first+1;
return arr[temp];
}
public Integer peek(){
if(size==0){
return null;
}
return arr[first];
}
public static void main(String[] args) {
P68_ArrayQueue queue=new P68_ArrayQueue(4);
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.peek());
}
}