用数组结构实现大小固定的队列和栈
package exercise;
import java.util.Arrays;
/*
用数组结构实现大小固定的队列和栈
*/
public class exercise1{
//用数组实现大小固定的栈
public static class ArrayStack
{
private Integer[] mystack;
//index始终指向栈顶的元素
private Integer index=-1;
public ArrayStack(int initsize) {
if (initsize<0){
throw new IllegalArgumentException("栈的长度必须大于0!");
}
mystack=new Integer[initsize];
}
//返回栈顶元素
public Integer peak(){
if (index==-1){
System.out.println("栈为空,无法读取栈顶元素!!!");
return null;
}
else return mystack[index];
}
//栈中加元素
public void push(Integer obj){
if(index==mystack.length-1) {
throw new ArrayIndexOutOfBoundsException("数组已经满了,添加失败!");
}
mystack[++index]=obj;
}
//栈中弹出元素
public Integer pop(){
if (index==-1){
throw new ArrayIndexOutOfBoundsException("数组为空,读取失败!");
}
else return mystack[index--];
}
public static void main(String[] args) {
ArrayStack a=new ArrayStack(5);
a.push(1);
a.push(3);
a.push(9);
a.push(91);
System.out.println("压栈操作");
System.out.println(Arrays.toString(a.mystack));
System.out.println("peak操作");
System.out.println(a.peak());
System.out.println("出栈操作");
System.out.println(a.pop());
System.out.println(a.pop());
System.out.println(a.pop());
//// System.out.println("出栈越界");
//// System.out.println(a.pop());
//// System.out.println(a.pop());
// System.out.println("压栈越界");
// a.push(1);
// a.push(3);
// a.push(9);
// a.push(91);
// a.push(91);
// a.push(91);
}
}
//---------------------------------------------------------------
/*
固定数组实现队列
start和end最初都指向myQueue[0]
每加上一个数end++;
每减一个数start++;
size来判断数组是队列是否犯了
当start和end走到数组的结尾是,在重新指向myQueue[0]
*/
//用数组实现大小固定的栈=队列
public static class Queue{
private Integer[] myQueue;
private Integer size;//size判断是否为空
private Integer start;
private Integer end;
public Queue(int initialize){
if (initialize<0){
throw new IllegalArgumentException("队列大小必须大于0!");
}
myQueue=new Integer[initialize];
size=0;//
start=0;
end =0;
}
//返回栈顶元素
public Integer peak(){
if (size==0){
throw new ArrayIndexOutOfBoundsException("队列为空!");
}
return myQueue[start];
}
public void push(Integer i){
if (size==myQueue.length) {
throw new ArrayIndexOutOfBoundsException("队列满了!!!");
}
size++;
myQueue[end]=i;
end=end==myQueue.length-1?0:end+1;
}
public Integer pop(){
if (size==0){
throw new ArrayIndexOutOfBoundsException("队列空了!!!");
}
size--;
int tmp=myQueue[start];
start=start==myQueue.length-1?0:start+1;
return tmp;
}
public void printQueue(){
int n=start;
int count=0;
System.out.printf("[ ");
while (count<size){
System.out.print(" ");
System.out.print(myQueue[n]);
n=n==myQueue.length-1?0:n+1;
count++;
}
System.out.printf(" ]");
System.out.println();
}
public static void main(String[] args) {
Queue q=new Queue(4);
q.push(3);
q.push(4);
q.push(5);
q.push(6);
q.printQueue();
q.pop();
q.pop();
q.push(1);
q.push(2);
q.printQueue();
}
}
}