Guest Article: By Sahil Bora
sahil

Sahil Bora is the founder and proprietor of C++ Better Explained. He is currently an engineering student at RMIT University Melbourne, Australia.

What is a stack?

A stack is a data structure used commonly in several programming languages. The reason why it is named a stack is because it’s structure as a collection of elements stacked on top of each other. An analogy to visualize what a stack is to picture several books stacked on top in a pile. In real life, the only way we can remove a book in a pile without affecting the others stacked in the pile is to remove the top book. Just like the analogy, the stack only allows the data operations at one end only, which is the top element of the stack.

Stacks in programming

SEE ALSO: More About Stack Operations

Operations of a stack

The stack data structure follows the LIFO system which stands for last in first out. Variable sizes are fixed at compile time and cannot be resized. With variables in stack memory, they are always in the function based memory allocation. The two operations of a stack include:

Push – Storing an element into the stack

The process of pushing a variable in the stack is to see if the stack is full. If the stack is full it will not proceed further, but if the stack is not full, it will increment to the next empty spot. This will allow the data element to be inserted, where the top is pointing.

push operation stack

push operations stack

Pop – Removing an element from the stacks

A pop operating in a stack allows accessing the content while deleting it from the stack. The process of the pop operation involves checking to see if the stack is empty. If it is empty, it will end but if it’s not empty, access to the variable pointed on top will be granted. The value at the top will then be decreased by one.

pop operation in stacks

Have something to discuss on stacks?? Please share in comments.

Follow us on Facebook, Google Plus and Twitter.