public class ReverseStack {
public void reverse(Stack stack) throws Exception{
if(stack.isEmpty()){
return;
}
Element e = stack.pop();
reverse(stack);
addBottom(stack, e);
}
public void addBottom(Stack stack, Element e) throws Exception{
if(stack.isEmpty()){
stack.push(e);
return;
}
Element ee = stack.pop();
addBottom(stack, e);
stack.push(ee);
}
/**
* @param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
try {
stack.push(new Element(1));
stack.push(new Element(2));
stack.push(new Element(3));
stack.push(new Element(4));
stack.push(new Element(5));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stack.print();
ReverseStack res = new ReverseStack();
try {
res.reverse(stack);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stack.print();
}
}
栈翻转
最新推荐文章于 2022-01-21 12:37:18 发布