package abc;import java.util.Stack;/**
* 实现栈的逆序,仅用递归
*/publicclassP03ReverseStack{publicstaticvoidmain(String[] args){
Stack<Integer> test =newStack<Integer>();
test.push(1);
test.push(2);
test.push(3);
test.push(4);
test.push(5);reverse(test);while(!test.isEmpty()){
System.out.println(test.pop());}}privatestaticvoidreverse(Stack<Integer> stack){if(stack.empty()){return;}int tmp =getLast(stack);reverse(stack);
stack.push(tmp);}privatestaticintgetLast(Stack<Integer> stack){int result = stack.pop();if(stack.empty()){return result;}else{int last =getLast(stack);
stack.push(result);return last;}}}
栈排序
package abc;import java.util.Stack;/**
* 一个栈中元素类型为整型,需要将该栈从顶到底按照从大到小顺序排序,只允许申请一个栈
*/publicclassP05SortStack{publicstaticvoidmain(String[] args){
Stack<Integer> stack =newStack<Integer>();
stack.push(3);
stack.push(1);
stack.push(6);
stack.push(2);
stack.push(5);
stack.push(4);sortStack(stack);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());}privatestaticvoidsortStack(Stack<Integer> stack){if(stack.empty()){return;}
Stack<Integer> help =newStack<Integer>();while(!stack.isEmpty()){int cur = stack.pop();// get top of stackwhile(!help.isEmpty()&& help.peek()< cur){
stack.push(help.pop());// push back in stack if top of help > top of stack}
help.push(cur);// push in help}while(!help.isEmpty()){
stack.push(help.pop());}}}