What would be the output of this?
This was a homework assignment given to me and I got the answer (listed later), but I was wondering if anyone could check it over and see if i'm correct:
a)
Code :
//Assume that you can store and retrieve variables of type int on stack
item1 = 1;
item2 = 0;
item3 = 4;
stack.push(item2); // push puts one item on top of stack
stack.push(item1);
stack.push(item1 + item3);
item2 = stack.top; //retrieves node info at top of stack
stack.push(item3*item3);
stack.push(item2);
stack.push(3);
item1 = stack.top();
stack.pop(); // pop() removes top item from stack
System.out.println(item1 + " " + item2 + " " + item3);
while(!stack.isEmpty()){
item1 = stack.top();
stack.pop();
System.out.println(item1);
}
My result is:
3 5 4
5
16
5
1
0
b)
Code :
item1 = 4;
item3 = 0;
item2 = item1+1;
stack.push(item2);
stack.push(item2+1);
stack.push(item1);
item2 = stack.top();
stack.pop();
item1 = item2+1;
stack.push(item1);
stack.push(item3);
while(!stack.isEmpty()){
item3 = stack.top();
stack.pop();
System.out.println(item3);
}
System.out.println(item1 + " " + item2 + " " + item3);
My result is:
0
5
6
5
5 4 5
Re: What would be the output of this?
What happened when you wrote a small program that runs this?
Re: What would be the output of this?
They look both correct. Not too hard with pen and paper (and of course I could not find any of them :P).