Data STR Chapter 4
Data STR Chapter 4
A stack is an Abstract Data Type (ADT), that is popularly used in most programming languages.
It is named stack because it has the similar operations as the real-world stacks, for example – a
pack of cards or a pile of plates, etc.
The stack follows the LIFO (Last in - First out) structure where the last element inserted would
be the first element deleted.
Properties of Stack
A Stack is a linear data structure that holds a linear, ordered sequence of elements. It is an
abstract data type. A Stack works on the LIFO process (Last In First Out), i.e., the element that
was inserted last will be removed first. To implement the Stack, it is required to maintain a
pointer to the top of the Stack, which is the last element to be inserted because we can access the
elements only on the top of the Stack.
A stack is a widely used data structure with unique characteristics which differentiate it from
other data structures. Below are its key features:
A stack follows the LIFO principle: Last In, First Out -- the last inserted element will be
the first to get removed.
Insertion and deletion are allowed at one end only, i.e., the 'top' of the stack.
The 'base' of the stack points to the first inserted element in the stack and the 'top' of the
stack points to the last inserted element.
Operation on Stack
2. POP: POP means to delete an element from the Stack. Before deleting an element, make sure
to check if the Stack Top is NULL, i.e., TOP=NULL. If this condition goes true, it means the
Stack is empty, and no deletion operation can be performed, and even if we try to delete, then the
Stack underflow message will be generated.
Algorithm:
Step-1: If TOP= NULL
Print “Underflow”
Goto Step 4
Step-2: Set VAL= Stack[TOP]
Step-3: Set TOP= TOP-1
Step-4: END
3. PEEK: When we need to return the value of the topmost element of the Stack without deleting
it from the Stack, the Peek operation is used. This operation first checks if the Stack is empty,
i.e., TOP = NULL; if it is so, then an appropriate message will display, else the value will return.
Algorithm:
Step-1: If TOP = NULL
PRINT “Stack is Empty”
Goto Step 3
Step-2: Return Stack[TOP]
Step-3: END
Implementation of Stack
There are two ways to implement a stack –
Using array
Using linked list
When we implement stack uisng array we take the direction of the stack i.e the direction
in which elements are inserted towards right.
isempty()- Now that we know that the stack is empty when top is equal to -1 we can use
this to implement our isempty() function i.e. when top == -1 retrun true else return false.
push()- To push an element into the stack we will simply increment top by one and insert
the element at that position. While inserting we have to take care of the condition when
the array is full i.e. when top == SIZE-1;
pop()- To pop an element from the stack we will simple decrement top by one which will
simply mean that the element is no longer the part of the stack. In this case we have to
take care of the condition when the stack is empty i.e top == -1 then we cannot perform
the pop operation.
show_top()- we will simply print the element at top if the stack is not empty.
Lets say we have an stack with one element i.e 2 and we have to insert ot push an element
3 to this stack.
Output
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
In the above program, the push() function takes argument val i.e., value to be
pushed into the stack. If a top is greater than or equal to n, there is no space in
a stack and overflow is printed. Otherwise, val is pushed into the stack. The code snippet for this
is as follows.
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
The pop() function pops the topmost value of the stack, if there is any value. If
The display() function displays all the elements in the stack. It uses a for loop to do so. If there
are no elements in the stack, then Stack is empty is printed. This is given below.
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
}else
cout<<"Stack is empty";
}
The function main() provides a choice to the user if they want to push, pop or display the stack.
According to the user response, the appropriate function is called using switch. If the user enters
an invalid response, then that is printed. The code snippet for this is given below.
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
In the above program, the structure Node is used to create the linked list that is implemented as
a stack. The code is given below.
struct Node {
int data;
struct Node *next;
};
The push() function takes argument val i.e., value to be pushed into the stack.
Then a new node is created and val is inserted into the data part. This node is added to the front
of the linked list and top points to it. The code snippet for this is as follows.
void push(int val) {
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}
The pop() function pops the topmost value of the stack, if there is any value. If the stack is empty
then underflow is printed. This is given as follows.
void pop() {
if(top==NULL)
cout<<"Stack Underflow"<<endl;
The display() function displays all the elements in the stack. This is done by using ptr that
initially points to top but goes till the end of the stack. All the
The function main() provides a choice to the user if they want to push, pop or
display the stack. According to the user response, the appropriate function is called using switch.
If the user enters an invalid response, then that is printed. The code snippet for this is given
below.
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
Application of Stack
1. A Stack can be used for evaluating expressions consisting of operands and operators.
2. Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
3. It can also be used to convert one form of expression to another form.
4. It can be used for systematic Memory Management.
Advantages of Stack
1. A Stack helps to manage the data in the ‘Last in First out’ method.
2. When the variable is not used outside the function in any program, the Stack can be used.
3. It allows you to control and handle memory allocation and deallocation.
4. It helps to automatically clean up the objects.
Disadvantages of Stack
1. It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
2. It has very limited memory.
3. In Stack, random access is not possible.
Infix notation is a method of writing mathematical expressions where the operators are placed
between the operands. It is the most commonly used notation in mathematics and everyday
The kind of notation known as Postfix Expression, also referred to as Reverse Polish Notation,
places the operator after the operand. For instance, if the infix expression is x + y, the postfix
notation for that expression is x y +. The process of converting infix to postfix expressions will
be thoroughly covered.
Since postfix expressions are simpler to evaluate and without overhead brackets, they are seen as
superior than infix expressions.
Understanding how to switch between different notations is crucial. We will walk through the
process of changing from infix to postfix in this section. For the conversion described above, a
stack data structure will be used. We can transform expressions that contain operators, operands,
and brackets (‘(‘). All of these will be taken into account when converting the expression.
We are initially given an infix expression to translate into postfix notation. After being parsed
from left to right, the infix notation is changed to postfix. Assuming the postfix expression is
initially empty, the following steps will be used to fill it out:
Initialize an empty stack and an empty string for the postfix expression.
Scan the infix expression from left to right.
If the scanned character is an operand (number or variable), append it to the postfix string.
If the scanned character is an open parenthesis ‘(‘, push it onto the stack.
If the scanned character is an operator (+, -, *, /, etc.), do the following:
a. While the stack is not empty and the top of the stack is an operator with higher or equal
precedence to the current operator, pop operators from the stack and append them to the postfix
string.
b. Push the current operator onto the stack.
If the scanned character is a close parenthesis ‘)’, do the following:
a. Pop operators from the stack and append them to the postfix string until an open parenthesis is
encountered (and discard the open parenthesis).
Repeat steps 3-6 until all characters in the infix expression have been scanned.
Pop any remaining operators from the stack and append them to the postfix string.
The resulting string in the postfix notation is the desired output.
Infix Expression:
Let’s perform a dry run of the aforementioned infix expression to determine the appropriate
postfix expression.
Left to right parsing is used for the string above. The table below shows, for each token, the
elements in the stack and the corresponding postfix expression up to that point:
K K
+ +
L + KL
– – KL+
M – KL+M
* -* KL+M
N -* KL+MN
+ + KL+MN*–
( +( KL+MN*–
O +(^ KL+MN*–O
^ +(^ KL+MN*–O
P +(^ KL+MN*–OP
) + KL+MN*–OP^
* +* K L + M N* – O P ^
W +* K L + M N* – O P ^ W
/ +/ K L + M N* – O P ^ W *
U +/ K L + M N* – O P ^W * U
/ +/ K L + M N* – O P ^W * U /
V +/ K L + M N* – O P ^ W * U / V
* +* K L + M N* – O P ^W * U / V /
T +* K L + M N* – O P ^W * U / V / T
+ + K L + M N* – O P ^W * U / V / T * +
Q + K L + M N* – O P ^W * U / V / T * + Q
K L + M N* – O P ^W * U / V / T * + Q+