Docsity

Stack Data Structure: LIFO Principle, Implementation, and Applications, Schemes and Mind Maps of Computer science

Partial preview of the text

Download Stack Data Structure: LIFO Principle, Implementation, and Applications and more Schemes and Mind Maps Computer science in PDF only on Docsity!

Stacks

Stack is a linear data structure which stores its elements in an ordered

manner

where do we need stacks in computer

science?

Ans: function calls

Example:

Executing function A. In the course of its execution, function A calls another

function B. Function B in turn calls another function C, which calls function D.

Whenever a function calls another function, the calling function is pushed onto

the top of the stack. This is because after the called function gets executed, the

control is passed back to the calling function

Now when function E is executed, function D will be removed from the top of the

stack and executed. Once function D gets completely executed, function C will be

removed from the stack for execution. The whole procedure will be repeated until all

the functions get executed.

Stacks can be implemented using either arrays or linked lists

  • In the computer’s memory, stacks can be represented as a linear array.

Every stack has a variable called TOP associated with it, which is used to store the address of

the topmost element of the stack.

  • It is this position where the element will be added to or deleted from. There is another variable called

MAX, which is used to store the maximum number of elements that the stack can hold.

Stack_arr[]

In an array insertion and deletion can be done in any place

Stack_arr[] is an array implementation of stack so it can perform insertion/deletion at the end only

Before inserting the value, first check if TOP=MAX–1 , because if

that is the case, then the stack is full and no more insertions can be

done.

If an attempt is made to insert a value in a stack that is already

full, an OVERFLOW message is printed

The push operation is used to insert an element into the stack.

The new element is added at the topmost position of the stack.

For push operation top has to be incremented by 1

Then value can be inserted on that top.

Peek Operation

Peek is an operation that returns the value of the topmost

element of the stack without deleting it from the stack

Peek operation first checks if the stack is empty, i.e., if TOP = NULL,

then an appropriate message is printed, else the value is returned

Write a program to perform Push, Pop

and operations on a stack