问题
如何只用一个数组实现两个栈?并且保证只要数组中海油剩余空间,不抛出异常
思路
1.初始化两个下标变量分别指向数组的左右两端
2.左边的下标指示第一个栈,右边的下标指示第二个栈
3.如果需要对第一个栈执行元素入栈操作,那么将元素赋值到左边下标变量指示的位置
4.如果需要对第二个栈执行元素入栈操作,那么将元素赋值到右边下标变量指示的位置
5.第一个栈向右增长,第二个栈向左增长
代码
/**
* 使用一个数组实现两个栈
* 栈和数组综合考察
*/
public class ArrayWithTwoStacks {
/*
元数据数组
*/
private int[] dataArray;
/*
数组容量
*/
private int size;
/*
概念栈StackId=1的栈的指针
*/
private int topOne;
/*
概念栈StackId=1的栈的指针
*/
private int topTwo;
public ArrayWithTwoStacks(int size) {
//两个栈存在的边界条件size>=2
if (size < 2) {
throw new IllegalStateException("size < 2 is no persmissible");
}
dataArray = new int[size];
this.size = size;
topOne = -1;
topTwo = size;
}
/**
* 入栈操作
*
* @param stackId
* @param data
*/
public void push(int stackId, int data) {
//是否满栈
if (topOne + 1 == topTwo) {
throw new IllegalStateException("Array is full!");
//可以参入数组扩容操作,对当前数组现有元素进行重编,初始化栈指针
}
if (stackId == 1) {
dataArray[++topOne] = data;
} else if (stackId == 2) {
dataArray[--topTwo] = data;
} else {
return;
}
}
/**
* 出栈
*
* @param stackId
* @return
*/
public int pop(int stackId) {
if (stackId == 1) {
if (topOne == -1) {
throw new EmptyStackException();
}
return dataArray[topOne--];
} else {
if (topTwo == size) {
throw new EmptyStackException();
}
return dataArray[topTwo++];
}
}
/**
* 栈顶元素
*
* @param stackId
* @return
*/
public int top(int stackId) {
if (stackId == 1) {
if (topOne == 1) {
throw new EmptyStackException();
}
return dataArray[topOne];
} else {
if (topTwo == this.size) {
throw new EmptyStackException();
}
return dataArray[topTwo];
}
}
/**
* 栈非空
*
* @param stackId
* @return
*/
public boolean isEmpty(int stackId) {
if (stackId == 1) {
return topOne == -1;
} else if (stackId == 2) {
return topTwo == this.size;
} else {
return true;
}
}
}
两个栈的push(入栈)和pop(出栈)操作的时间复杂度都为O(1),空间复杂度为O(1)