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();
}
}栈翻转
最新推荐文章于 2024-04-07 22:03:36 发布
3825

被折叠的 条评论
为什么被折叠?



