如何制作堆栈的副本,但仅使用Stack 类中的push
、pop
、peek
和isEmpty
方法保留原始堆栈?这甚至可能吗?
public static <E> Stack<E> copy(Stack<E> s){
s2 = new Stack<E>();
if(s.isEmpty())
return null;
while(!s.isEmpty())
{
E elem = s.peek();
s2.push(elem);
s.pop();
}
return s2;
}
public static void main(String[] args) {
StackCopy sCopy = new StackCopy();
Stack<Integer> s = new Stack<Integer>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s2 = sCopy.copy(s);
System.out.print("stack1 = ");
while(!s.isEmpty()){
System.out.print(s.peek() );
s.pop();
}
System.out.println("Stack 2 = ");
while(!s2.isEmpty()){
System.out.print(s2.peek() );
s2.pop();
}
}