分析:用数组实现大小固定的栈和队列
1、实现栈结构:栈结构是先进后出,只需要一个数组和一个记录位置的变量size,当进来一个元素,size++,当出去一个元素则size--。
2、实现队列结构:队列先进先出,需要一个数组和三个变量,size记录已经进来了多少个元素,in记录刚进来的元素放置在哪个位置,out表示用户要求弹出元素所在的位置。其中size还是in与out的操作的关键信息。
实现:
栈的实现:
package stack1;
public class Stack1 {
public static class MyStack{
private int size;//指针位置,也表示栈已经压了多少
private int[]arr;
MyStack(int iniSize){//构造方法初始化数组
arr = new int[iniSize];
size = 0;
}
public void push(int num){
if(size == arr.length){
throw new RuntimeException("栈下标越界!");
}
arr[size++] = num;
}
public int pop(){
if(size == 0){
throw new RuntimeException("栈中已经没有元素可以弹出!");
}
return arr[--size];
}
public int peek(){
if(size == 0){
throw new RuntimeException("栈中已经没有元素可以弹出!");
}
return arr[size];
}
}
public static void main(String[] args) {
int len = 13;
MyStack myStack = new MyStack(len);
for (int i = 0; i < len; i++) {
myStack.push(i);
}
for (int i = 0; i < len; i++) {
System.out.println(myStack.pop());
}
}
}
队列的实现:
package stack1;
public class Queue1 {
public static class MyQueue{
private int out;//新进来的数 放这
private int in;//用户要求弹出的数
private int size;//已经进队列的个数
private int arr[];
public MyQueue(int iniSize){
arr = new int[iniSize];
size = 0;
in = 0;
out = 0;
}
public void push(int num){
if(size==arr.length){
throw new RuntimeException("the queue is full!");
}
size++;//大小扩展一个
arr[in] = num;//赋值
in = in==arr.length-1 ? 0 : in+1;//如果已经到达数组末尾就重新等于0
}
public int pull(){
if(size==0){
throw new RuntimeException("the queue is empty!");
}
size--;
int t = out;//记录
out = out==arr.length-1 ? 0 : out+1;//如果已经到达数组末尾就重新等于0
return arr[t];
}
public int peek(){
if(size==0){
throw new RuntimeException("the queue is empty!");
}
return arr[out];
}
}
public static void main(String[] args) {
int iniSize = 3;
MyQueue myQueue = new MyQueue(iniSize);
myQueue.push(12);
myQueue.push(13);
myQueue.push(15);
System.out.println(myQueue.pull());
System.out.println(myQueue.pull());
System.out.println(myQueue.pull());
myQueue.push(23);
myQueue.push(24);
System.out.println(myQueue.pull());
System.out.println(myQueue.peek());
}
}

333

被折叠的 条评论
为什么被折叠?



