Q4. When creating stacks what is the meant by the top value ?
How is it’s initialization
performed? Which value is it initialized to and why?
Stack is a data structure which stores data in it in Last In First Out (LIFO) order. When creating stacks, top value indicates the top-most element of the stack, i.e, the element which is inserted at last or the most recently inserted element in the stack. All the insertion and deletion operations of stack is done from the top of the last element that is inserted.
In C++, peek() and stack.top() function is used to access the top of the stack. Suppose in starting, no element is there in the stack. At that time, top value of the stack will be below zero or -1.
Now suppose we push an element in this stack.
stack<int> mystack;
mystack.push(8);
Now the top value will automatically get initialized as 8.
If you push another element in this stack, say mystack.push(2);, now the top value will get initialized as 2.
Lets assume that now you want to change the top value of the stack without pushing any other element in the stack. In this case, you can use stack.top() function as shown below.
mystack.top()=5;
Now instead of 2, top value will get initialized as 5.
If you still have any doubt/query regarding the answer then let me know in comment. If it helps, kindly give an upVote to this answer.
Get Answers For Free
Most questions answered within 1 hours.