Stack: 2.2.1. Adding An Element Onto The Stack (Push Operation)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

STACK

2.I.Introduction

A stack is an Abstract Data Type (ADT), commonly used in most programming languages. Stack is a LIFO
data structure in which only two operations are allowed i.e., pushing and popping. Pushing is the
process of adding an element to the stack top whereas popping is a process of removing an item from
the stack top. For easily understanding the concept of stack just imagine a stack as a vertical cylinder
which is closed at the bottom. So just imagine that we have to put some coins into the cylinder. What
will we do? We will put the coins from the top of the cylinder. Each time when you put a cylinder it will.
So, we can place a coin only on the top of the last inserted coin and also, we can remove the coin only
from the top of the cylinder. That is, the coin which was inserted last will be removed from the search.
Then we have to know what a stack top is. stack top is nothing but the position of the last inserted item
in a stack.

Stack can be implemented either statically or dynamically. Static implementation of a stack is possible
only with the help of an array and the dynamic implementation of the stack is performed with the help

of a linked list. Another two concepts related with the stack are stack overflow and stack underflow.
Stack overflow is a condition in which there is no further space in the stack for the insertion. And the
stack underflow is a condition in which the stack is empty.

2.2.ARRAY IMPLEMENTATION OF A STACK.

In this chapter we will be discussing the static implementation.

2.2.1. Adding an element onto the stack (Push Operation)

Adding an element into the top of the stack is referred to as push operation. Push operation involves
following two steps.
1. Increment the variable Top so that it can now refer to the next memory location.
2. Add an element at the position of the incremented top. This is referred to as adding a new
element at the top of the stack.

Stack will face a condition of overflow when we try to insert an element into a completely filled stack
therefore, our main function is to check whether stack is overflow or not before insertion.

Algorithm:

push (STACK,ITEM )

Description: Here STACK is an array with MAX locations.

TOP points to the top most element and ITEM is the value to be inserted.

1. If TOP == MAX-1 Then [Check for overflow]

Print: Overflow

Else

Set TOP = TOP + 1 [Increment TOP by 1]

Set STACK[TOP] = ITEM [Assign ITEM to top of STACK]

Print: ITEM inserted

End of If

2. Exit

Time Complexity: o(1)

2.2.2.Deletion of an element from a stack (Pop Operation)

Deletion of an element from the top of the stack is called pop operation. The value of the variable top
will be decremented by 1 whenever an item is deleted from the stack. The top most element of the
stack is stored in another variable and then the top is decremented by 1. the operation returns the
deleted value that was stored in another variable as the result.

The underflow condition occurs when we try to delete an element from an already empty stack.

Algorithm:

pop (STACK )

Description: Here STACK is an array with MAX locations.

TOP points to the top most element and ITEM contains the value popped from STACK.

1. If TOP == -1 Then [Check for underflow]


Print: Underflow

Else

Set ITEM = STACK[TOP] [Assign top of STACK to ITEM]

Set TOP = TOP - 1 [Decrement TOP by 1]

Print ITEM “removed”

End If

2. Return

Time Complexity: o(1)

2.2.3 PROGRAM TO IMPLEMENT A STACK USING ARRAY

#include<stdio.h>

#include<conio.h>

#define MAX 5

void push(int[],int);

void pop(int[]);

void disp(int[]);

int top=-1;

void main()

int ch,item,stk[10];

clrscr();

do

printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\nEnter your choice");

scanf("%d",&ch);

switch(ch)

{ case 1:

printf("Enter the item to be pushed");

scanf("%d",&item);

push(stk,item);

break;
case 2:

pop(stk);

break;

case 3:

disp(stk);

break;

case 4:

exit(0);

default:

printf("\nInvalid option");

}while(ch!=4);

getch();

//Function push()

void push(int stk[10], int item)

if(top==MAX-1)

printf("stack overflow");

else

top++;

stk[top]=item;

printf("One item pushed");

//function pop()

void pop(int stk[10])

{
int item;

if(top==-1)

printf("stack underflow");

else

item=stk[top];

top--;

printf("\nOne item popped %d",item);

//function disp()

void disp(int stk[10])

int i;

if(top==-1)

printf("stack is empty");

else

for(i=top;i>=0;i--)

printf("\t%d",stk[i]);

2.3.Applications Of Stack

1. Stacks can be used for Conversion from one form of expression to another.


2. Stacks can be used for expression evaluation.
3. Stack is used to find the string reverse
4. Stacks can be used in recursive functions.
5. Stacks can be used for Memory Management.
6. Stack is used in compiler design

Before going to the details of the stack applications, let us see what are the different methods to
represent a mathematical expression. Mathematical expression can be represented in three different
ways. Prefix expression postfix expressions and infix expressions. We know that a mathematical
expression is a combination of operands and operators. And depending upon the position of the
operands and operators infix to prefix and postfix expression varies. In an infix expression which is
commonly used by the users the operators are placed in between the operands in the case of postfix
expressions the operators are placed after the operands. In a prefix expression the operators are placed
before the operands. Following are the examples of three types of expressions.

Infix notation: X + Y
Operators are written in-between their operands. This is the usual way we write expressions. An
expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C
together, then multiply the result by A, then divide by D to give the final answer."
Postfix notation (also known as "Reverse Polish notation"): X Y +
Operators are written after their operands. The infix expression given above is equivalent
to A B C + * D /

Prefix notation (also known as "Polish notation"): + X Y


Operators are written before their operands. The expressions given above are equivalent
to / * A + B C D

2.3.1Conversion of an Infix Expression to Postfix Expression

Algorithm for converting an infix expression to postfix expression:

Infixtopostfix(infix)

Description: Here infix is an infix expression and we have to obtain a corresponding postfix expression
and a stack STK is used.

Initially we have to scan the infix expression from left to right until the end of the infix expression until
the end of expression is encountered. While scanning from left to right we have to perform the required
operations depending on whether it is an operand and operator.

1) start
2) Add closing braces to the end of the infix expression and corresponding opening braces to the top of
the stack.
3) Scan infix from left to right until the end of the expression is encountered.
a) If an operand is encountered simply push the operand on to STK after incrementing the top
b) If an operand is encountered just add it to the postfix expression.
c) When a closing parenthesis is encountered
i) Pop and add to the postfix expression each operators until an opening bracket is
encountered
ii) Then remove the opening bracket from STK
d) If an operator is encountered
i)
repeatedly pop and add to the postfix expression all the operators having equal or higher
precedence than the operator encountered.
ii) Then add the operator on to STK
4) Stop

Program to implement infix to postfix conversion

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char infix[20],stk[10];

int l,i,top=-1;

clrscr();

printf("Enter the infix expression");

gets(infix);

l=strlen(infix);

//Adding closing bracket to the end of expression

infix[l]=')';

infix[++l]='\0';

//Pushing ( to stack

stk[++top]='(';

//scanning the expression from left to right

printf("\n The postfix expression is\n");

for(i=0;infix[i]!='\0';i++)

//checking for operand

if((infix[i]>='a'&&infix[i]<='z')|| (infix[i]>='A'&&infix[i]<='Z')||
(infix[i]>='0'&&infix[i]<='9'))

printf("%c",infix[i]);

//checking for opening bracket

else if(infix[i]=='(')
{

top++;

stk[top]=infix[i];

//checking for closing bracket

else if(infix[i]==')')

while(stk[top]!='(')

printf("%c",stk[top]);

top--;

top--;

//checking for operands

else if(infix[i]=='^')

while(stk[top]=='^')

printf("%c",stk[i]);

top--;

stk[++top]=infix[i];

else if(infix[i]=='*'||infix[i]=='/')

while(stk[top]=='*'||stk[top]=='/'||stk[top]=='^')

printf("%c",stk[i]);

top--;

stk[++top]=infix[i];
}

else if(infix[i]=='+'||infix[i]=='-')

while(stk[top]=='*'||stk[top]=='/'||stk[top]=='^'||stk[top]=='+'||stk[top]=='-')

printf("%c",stk[i]);

top--;

stk[++top]=infix[i];

else

continue;

getch();

2.3.2.Postfix Expression Evaluation.

For solving a mathematical expression, we need a prefix or postfix form. But usually, we use infix
notation to represent the mathematical expressions. In order to evaluate an infix expression, the
expression has to be converted to postfix form and then it is evaluated. We have already seen how
an infix expression can be converted to a postfix expression. In this algorithm we can see how to
evaluate a postfix expression.
Here also we have to use the stack data structure to solve the postfix expressions.
From the postfix expression, when some operands are found, push them onto the stack. When
some operator is found, two items are popped from the stack and the operation is performed in
the correct sequence. After that, the result is also pushed in the stack for future use. After
completing the whole expression, the final result is also stored in the stack top.
Consider an example :

Postfix expression: 84+62-/


Output:
The result is: 3
Algorithm for evaluating a postfix expression

postfixeval(postfix)

Description: Here infix is an infix expression and we have to obtain a corresponding postfix expression
and a stack STK is used.

Initially we have to scan the infix expression from left to right until the end of the infix expression until
the end of expression is encountered. While scanning from left to right we have to perform the required
operations depending on whether it is an operand and operator.

1. Start
2. Repeatedly scan the postfix expression from left to right until the end of expression is
encountered.
a. If an operand is encountered push it to STK
b. If an operator is encountered
i. Pop two operands from the stack A and B respectively
ii. Evalauate B A and puch the result onto the stack
3. Pop from the stack the value of the expression
4. Stop

Program for evaluating a Postfix Expression

#include<stdio.h>

#include<conio.h>

void main()

char post[20];

int i,top=-1;

float stk[20],a,b,c,v ;

clrscr();

printf("enter the postfix expression");


gets(post);

puts(post);

for(i=0;post[i]!='\0';i++)

if(post[i]>='0'&&post[i]<='9')

top++;

stk[top]=post[i]-'0';

else if((post[i]>='a'&&post[i]<='z') ||(post[i]>='A'&&post[i]<='Z'))

printf("enter the value of operand %c",post[i]);

scanf("%f",&v);

top++;

stk[top]=v;

else

a=stk[top];

top--;

b=stk[top];

top--;

switch(post[i])

case '+':

c=b+a;

break;

case '-':

c=b-a;

break;

case '*':

c=b*a;
break;

case '/':

c=b/a;

break;

case '^':

c=pow(b,a);

break;

top++;

stk[top]=c;

}//for

printf("value of expression is %.2f",stk[top]);

getch();

2.3.3.String Reversal

In a data structure stack allow you to access last data element that you inserted to stack. So inorder to
find the reverse of a string we can push each character of the string onto the stack and when we pop
each letter from the stack we can obtain the reverse of the string.

Algorithm for string reversal

reverse(STR)

Description: Here a stack STK is used to find the reverse of the string

Initially we have to push each characters of the string to the stack and then it is popped back to obtain
the reverse
1. Start
2. Repeat until the end of the string STR is encountered

Increment top

Push STR[i] to the STK[TOP]

3. Repeat until the stack STK is empty

Print STK[TOP]

Decrement the stack top

4. Stop

Program to find the reverse of the string

#include<stdio.h>

#include<conio.h>

void reverse(char[]);

int top=-1;

char stk[20];

void main()

char s[20];

clrscr();

printf("enter a string");

gets(s);

reverse(s);

getch();

void reverse(char s[20])

int i;

//pushing characters to stack

for(i=0;s[i]!='\0';i++)

{
stk[++top]=s[i];

//popping each character from stack top

for(i=top;i>=0;i--)

printf("%c",stk[top--]);

Output:

enter a stringHello

olleH

2.3.4.Stack in Recursive Functions

"Recursion" is the technique of solving any problem by calling the same function again and again
until some breaking (base) condition where recursion stops and it starts calculating the solution
from there on. For eg. calculating factorial of a given number.Thus in recursion last function called
needs to be completed first.Now Stack is a LIFO data structure i.e. ( Last In First Out) and hence it is
used to implement recursion. In each recursive call, there is need to save the current values of
parameters, local variables and the return address (the address where the control has to return
from the call).Also, as a function calls to another function, first its arguments, then the return
address and finally space for local variables is pushed onto the stack.

Program to find the factorial of a number

#include<stdio.h>

#include<conio.h>

int find_factorial(int);

void main()

int num, fact;

printf("\nEnter any integer number:");

scanf("%d",&num);

fact =find_factorial(num);

printf("\nfactorial of %d is: %d",num, fact);

getch();
}

int find_factorial(int n)

//Factorial of 0 is 1

if(n==0)

return(1);

//Function calling itself: recursion

return(n*find_factorial(n-1));

Output:

Enter any integer number: 4

factorial of 4 is: 24

1. Recursion is extremely useful and extensively used because many problems are elegantly
specified or solved in a recursive way.
2. The example of recursion as an application of stack is keeping books inside the drawer and the
removing each book recursively.

You might also like