I though in java, when you do object1=object2
, you will copy the reference of object2
to object1
, so object1
and object2
point" to the same object. Is it right?
I wrote a function to sort a stack.
import java.util.Stack;
public class sortStack {
public static void main(String[] str) {
Stack<Integer> s = new Stack<Integer>();
s.push(2);
s.push(21);
s.push(43);
s.push(3);
s.push(87);
s.push(2);
s.push(12);
s.push(10);
s.push(25);
sortStack(s);
while (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
public static void sortStack(Stack<Integer> src) {
Stack<Integer> dst = new Stack<Integer>();
Stack<Integer> buf = new Stack<Integer>();//buffer
while (!src.isEmpty()) {
int v = src.pop();
if (dst.isEmpty()) {
dst.push(v);
}
while (!dst.isEmpty() && dst.peek() > v) {
buf.push(dst.pop());
}
dst.push(v);
while (!buf.isEmpty()) {
dst.push(buf.pop());
}
}
src = dst;
//Print:
//while(!src.isEmpty()){
// System.out.print(src.pop()+" ");
//}
}
}
I couldn't get any output from the class. If I uncomment the print part, it words fine.
I don't understand the s
stack is empty after I call the function. I already assign dst
to s, so s should point to the dst
stack, right?
Please help! Thanks!