题目:
给定一个栈,只使用栈的操作(pop和push),实现栈的逆置。
算法:
1、利用递归函数reserveStack(),pop栈顶元素,直至栈空。
2、每次递归向上一步骤时,利用insertStaBot递归函数,将上一步中出栈的元素插入栈底。
import java.util.Arrays;
public class ArrayStack {
private int top;
private int capacity;
private int[] array;
public ArrayStack(int capacity) {
this.top = -1;
this.capacity = capacity;
this.array = new int[capacity];
}
public boolean isEmpty(){
return (top==-1);
}
public boolean isFull(){
return (top==capacity-1);
}
public void push(int data){
if(this.isFull()){
this.DoubleStack();
}
array[++top] = data;
}
public int pop(){
if(this.isEmpty()){
System.out.println("the Stack is empty");
return -1;
}else {
return array[top--];
}
}
public void reverseStack(ArrayStack stack){
if(stack.isEmpty()){
return;
}
int temp = stack.pop();
reverseStack(stack);
insertStaBot(stack,temp);
}
public void insertStaBot(ArrayStack stack,int data){
if(stack.isEmpty()){
stack.push(data);
return;
}
int temp = stack.pop();
insertStaBot(stack,data);
stack.push(temp);
}
public void deleteStack(){
top = -1;
}
@Override
public String toString() {
StringBuilder st = new StringBuilder();
for(int i=0;i<array.length;i++){
st.append(array[i]+" ");
}
return st.toString();
}
}
class test1 {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(10);
for(int i =0;i<10;i++){
stack.push(i);
}
System.out.println("逆置之前:"+stack.toString());
stack.reverseStack(stack);
System.out.println("逆置之后:"stack.toString());
}
}
运行结果: