最近在看左神的算法课,理解之后在此将代码记录下来
将数组转换成栈:
class ArrayToStack {
private Integer[] arr;//数据栈
private Integer index;//索引位
public ArrayToStack(int initSize) {
if (initSize < 0) {
throw new ArrayIndexOutOfBoundsException("参数不能小于0");
}
arr = new Integer[initSize];
index = 0;
}
public void push(int num) {
if (index == arr.length) {
throw new ArrayIndexOutOfBoundsException();
}
arr[index++] = num;
}
public Integer pop() {
if (index <= 0) {
throw new ArrayIndexOutOfBoundsException();
}
return arr[--index];
}
}
问题一:
如何仅用队列结构实现栈结构?
//两个队列实现一个栈
class TwoQueueStack{
private Queue<Integer> dataQueue;
private Queue<Integer> helpQueue;
public TwoQueueStack(){
dataQueue = new LinkedList<>();
helpQueue = new LinkedList<>();
}
public void push(int item){
dataQueue.add(item);
}
public Integer pop(){
if(dataQueue.isEmpty()){
throw new RuntimeException("栈为空");
}
while (dataQueue.size() > 1){
helpQueue.add(dataQueue.poll());
}
int num = dataQueue.poll();
swap();
return num;
}
public Integer peek(){
while (dataQueue.size() > 1){
helpQueue.add(dataQueue.poll());
}
int num = dataQueue.peek();
helpQueue.add(num);
swap();
return num;
}
private void swap(){
Queue<Integer> temp = helpQueue;
helpQueue = dataQueue;
dataQueue = temp;
}
}