用固定数组实现栈:(栈:先进后出)
- 需要一个变量(index)指示入栈位置同时也是当前出栈的位置(栈进出位置一致,所以只需要一个变量用来指示)判断栈是否为空或者为满时,只需要判断当前位置的小标
- 实现栈所需要实现的函数:(1)构造函数构建栈,(2)入栈函数push(3)出栈函数pop(4)得到栈顶的值peek
- Index=0时,当前栈空,index=arr.Length时,当前栈满
- 代码:
-
public static class Stack { Integer arr[]; Integer index; // 构建一个栈时的初始化 public Stack(int initSize) { if (initSize < 0) { throw new IllegalArgumentException("The init size is less than 0"); } arr = new Integer[initSize]; index = 0; } // 入栈 public void push(int a) { if (index == arr.length) throw new ArrayIndexOutOfBoundsException("队列已满,不能添加"); else { arr[index++] = a; } } public Integer peek() { if (index == 0) { System.out.println("栈为空,无元素查询"); //或者抛出异常或者不抛出异常返回null return null; } else { return arr[index-1]; } } public Integer pop() { if (index == 0) { throw new ArrayIndexOutOfBoundsException("栈为空,无元素出栈"); } else { return arr[--index]; } } }
用固定数组实现队列:(队列:先进先出)
- 由于队列的出队列与入队列并不在一个位置,存在队尾与队首,所以需要变量start与end分别记录入队位置与出队位置,另外,队列是循环形式的,所以需要判断队列是否为空,有两种方式,一种是借助start与恩典大小进行边界判断,另一种是,再增加一个变量size直接记录队列大小,判断是否空满,这样start与end相互独立无关,解耦和
- 实现栈所需要实现的函数:(1)构造函数构建队列,(2)入列函数push(3)出列函数poll(4)得到队列首的值peek
- Start指向队列头所在位置(即出队时元素所在位置),end指向队列尾的下一个位置(即下一个元素入队时要插入的位置)
public static class Queue{
Integer arr[];
Integer start;
Integer end;
Integer size;
Queue(Integer initSize){
if(initSize<0)
throw new IllegalArgumentException("The init size is less than 0");;
arr=new Integer[initSize];
start=0;
end=0;
size=0;
}
public void push(int a) {
if(size==arr.length)
throw new ArrayIndexOutOfBoundsException("队列已满,不能添加");
size++;
arr[end]=a;
end=(end+1)%arr.length;
}
//得到元素并不出队列
public Integer peek() {
if(size==0)
{System.out.println("队列为空");
return null;}
return arr[start];
}
public Integer poll() {
if(size==0)
{throw new ArrayIndexOutOfBoundsException("队列为空,无法出队");
}
size--;
int ans=start;
start=(start+1)%arr.length;
return arr[ans];
}
}
测试代码:
public static void main(String []args) {
Queue s1=new Queue(5);
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
// s1.push(6);
System.out.println(s1.poll());
System.out.println(s1.poll());
System.out.println(s1.poll());
System.out.println(s1.poll());
System.out.println(s1.poll());
// System.out.println(s1.poll());
s1.push(19);
s1.push(7);
System.out.println(s1.peek());
System.out.println(s1.poll());
System.out.println(s1.peek());
System.out.println(s1.poll());
}
}