java一个小问

来源:百度知道 编辑:UC知道 时间:2024/06/07 23:01:15
(a) [3 marks] What is the value of variable "answer",
after the following code has been executed ?

StackX s = new StackX(101); // A stack of ints
Queue q = new Queue(101); // A queue of ints
for (int i = 0; i <= 100; i++)
s.push(i);
while (!s.isEmpty())
q.insert(s.pop());
int answer = q.remove();

答案是100, 不知何解?

(a) [3 marks] What is the value of variable "answer",
after the following code has been executed ?

StackX s = new StackX(101); // A stack of ints
Queue q = new Queue(101); // A queue of ints
for (int i = 0; i <= 100; i++)
s.push(i);
到这里,stack大小为101,最上面的是100,queue还是空的
while (!s.isEmpty())
q.insert(s.pop());
插入一条stack最上面的一条,就是100进queue,queue的大小为1,最上面为100
int answer = q.remove();
取得queue的最上面的数据,并移除

s堆栈存了0-100,while语句将堆栈数据从100-0取出存入队列
q.remove()取出队首的值100。
堆栈是后进先出,队列是先进先出