In: Computer Science
Show what is written by the following segment of code, given item1, item2, and item3 are int variable:
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():
cout <<item3<<endl;
stack.Pop();
}
cout<<item1 <<endl <<item2<<endl<<item3<<endl;
Stack is linear data structure which follows LIFO (Last In First Out) order, which means the value which is last pushed (inserted) into the stack will be popped (deleted) first. Top in a stack points to the value which is last inserted.
The value of item1 = 4.
The value of item2 = item1 + 1, that is, it will be 5.
The value of item3 = 0.
stack.Push(item2), this statement pushes item2's value to the stack, which means 5 will be inserted into the stack.
stack.Push(item2 +1), this statement pushes item2 + 1 value to the stack, which means 6 will be inserted into the stack.
stack.Push(item1), this statement pushes item1's value to the stack, which means 4 will be inserted into the stack.
Values in stack are: 4, 6, 5 (from top to bottom).
item2 = stack.Top(), this statement changes the value of item2 with the value which is at the top (last inserted), so now item2's value is 4.
stack.Pop(), this will delete the element at top, so 4 gets deleted, and now the top points to 6. Now stack has only 6 and 5 in it.
item1 = item2 + 1, this statement increments item1's value by 1 = 5.
stack.Push(item1), this statement inserts item1's value into the stack, which is 5. Now stack has 5, 6, 5 (from top to bottom). Top points to 5.
Stack.Push(item3), this statement inserts item3's value into the stack, which is 0. Now stack has 0, 5, 6, 5 (from top to bottom). Top points to 0.
while (!stack.IsEmpty()), this loop terminates when the stack gets empty, i.e., have no value in it.
{
item3 = stack.Top(), this changes the value of item3 to the top most value of the stack.
cout <<item3<<endl, this statement prints item3's value.
stack.Pop(), this statement deletes the top most value of stack.
}
cout<<item1 <<endl <<item2<<endl<<item3<<endl, this prints the value of item1, item2 and item3, which 5, 4 and 5 respectively.
Final Output:
0
5
6
5
5
4
5