模拟栈的入栈和出栈
通过一个变量index来指向栈顶元素的位置。
public class Mstack {
private int size;
private int[] arr;
private int index;//指向栈顶的元素的位置
public Mstack(int initSize) {
if(initSize<0)
throw new IllegalArgumentException("数组初始长度有误!");
arr=new int[initSize];
index=0;
size=initSize;
}
public void push(int num) {
if(index<size) {
arr[index]=num;
index++;
}
else
System.out.println("push failed.");
}
public void pop() {
if(index>0) {
index--;
System.out.println("pop success:"+arr[index]);
}else
System.out.println("pop failed.");
}
public static void main(String[] args) {
Mstack mstack=new Mstack(3);
mstack.push(2);
mstack.push(3);
mstack.push(1);
mstack.pop();
}
}
模拟队列的出队和入队
通过三个变量,就可以不用移位来出队和入队。
变量start指向对头
变量end指向队尾
变量size数组包含有元素的实际长度
package SortArr;
public class Mqueue {
private int[] arr;
private int start;
private int end;
private int size;
public Mqueue(int initSize) {
if(initSize<0)
throw new IllegalArgumentException("数组长度有误!");
arr=new int[initSize];
start=0;
end=0;
size=0;//初始时start和end都指向0位置的元素,通过size来判断数组有无元素
}
public Integer peek() {
if(size>0)
return arr[start];
else
return null;
}
public void push(int num) {
if(size==arr.length)
System.out.println("队列已满!");
else
{
arr[end++]=num;
end%=arr.length;//当end指向数组的最后一个的下一个时,应转向指回0位置的元素
size++;//元素个数++
}
}
public Integer poll() {
if(size>0) {
size--;
System.out.println(arr[start]);
int t=start++;
start%=arr.length;//start同end一样,也要转向往回指0位置的元素
return arr[t];
}
else
return null;
}
public static void main(String[] args) {
Mqueue mqueue=new Mqueue(3);
mqueue.push(3);
mqueue.push(1);
mqueue.push(2);
mqueue.poll();
mqueue.push(6);
mqueue.poll();
mqueue.poll();
mqueue.poll();
}
}