0% found this document useful (0 votes)
73 views

Stacks Data Structures

The document discusses stacks as a data structure and their implementation using arrays. It defines stacks as having LIFO (last-in, first-out) behavior where elements are added and removed from the top. Basic stack operations like push, pop, peek and display are described along with algorithms. Overflow occurs when a stack is full while underflow happens when it is empty. An example C program is provided to implement a stack using an array with functions for push, pop and display.

Uploaded by

Anand Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Stacks Data Structures

The document discusses stacks as a data structure and their implementation using arrays. It defines stacks as having LIFO (last-in, first-out) behavior where elements are added and removed from the top. Basic stack operations like push, pop, peek and display are described along with algorithms. Overflow occurs when a stack is full while underflow happens when it is empty. An example C program is provided to implement a stack using an array with functions for push, pop and display.

Uploaded by

Anand Panchal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

2.

STACKS
Syllabus: Stacks (Computer Engineering)

The Stack as an ADT, Stack operations,


Array Representation of Stack, Link
Representation of Stack, Application of
stack – Recursion, Polish Notations.

Stacks (Information Technology)

The Stack ADT, Implementation of Stacks,


Applications.

Overview of Stack:

A stack is a data structure in which addition of new element OR


deletion of existing element always takes place at the same end,
which is called as ‘TOP’ of the stack. (Or sometimes it is also
called as Stack TOP).

One can imagine stack as a data structure whose one end is


sealed and we are allowed to process the data only from other
end. The element of a stack is added and get processed first,
hence it is supposed to have LIFO (Last in First Out) processing.

02TOP

46

50
To understand the concept of stack very easily, let us have a
simple day-to-day life example. Suppose we went restaurant for
dinner. Waiter serves us plates for dinner. Have you seen the
arrangement of plates in the kitchen? It is actually according to
stack manner, where removal of any random plate is not
possible. We have to remove plate which is on topmost of the
plate-stack.

Stack of plates

In a same way, even the element which is on the topmost of the


stack should be processed first. Processing in this case can be
anything .i.e. element can be added, deleted, viewed, Displayed
or any suitable data-processing.

A. STACK Operations :

There are some basic operations on stack which are described


below. These operations are very important as we are going to
implement them in next topic.

- PUSH (): - The Operation of adding new element on to the


stack is known as PUSH operation. After PUSH operation
TOP of the stack gets incremented. Before adding new
element onto the stack, we first check whether stack is
overflow or not (i.e. maximum element filling capacity is
reached). otherwise it is added directly onto the stack

The algorithm for PUSH operation is given below:

Algorithm: PUSH (element x, stack S)


{
If (stack = Full)
Print “stack overflow”;
Else
{
Increment TOP pointer
Fill the new element onto the stack
followed by TOP pointer.
}
STOP
}

- POP (): The operation of deleting element from the stack is


known as POP operation. The TOP pointer gets decremented
after POP operation. before doing POP operation we always
check whether stack is underflow ( stack is empty)
The algorithm for POP operation is:

Algorithm POP (stack S)


{
If (stack = empty)
Print “cannot delete element because it
is already empty”
Else
Decrement TOP pointer
STOP
}

- DISPLAY (): The operation prints all the values present in the
stack. We can implement this method using looping
structure of C (i.e. for loop).
The algorithm for DISPLAY operation is given below:

Algorithm DISPLAY (Stack S)


{
If (stack = empty)
Print “cannot DISPLAY elements as stack
is empty”
Else
For i= 0  TOP pointer
DISPLAY elements one by one
STOP
}

- EMPTY (): The operation of checking whether the stack is


empty or not is known as EMPTY operation. The TOP pointer
should be initialized to -1 in case of empty stack.
The algorithm for EMPTY operation is given below:

Algorithm EMPTY (Stack S)


{
if ( TOP==-1)
/* Stack Empty */
else
/* PUSH or POP or DISPLAY */
STOP
}

- PEEK () : The operation which gives element where TOP


pointer points to the stack is called as PEEK element .the
example of peek element is shown below:

10 20 30 40 50

PEEK ELEMENT (TOP)

Here PEEK () Function will return the value 50 because TOP


pointer points to the value 50.

To understand above operations easily let us take an example.


The example tabulated below gives brief idea that how the stack
operations are actually performed.

Operations Position of stack

Initialize stack S

Size (S) = 5 elements

TOP = -1

PUSH (3)
3
TOP ++ ;
PUSH (6)
3 6
TOP ++ ;

POP ()
3
TOP --

PUSH (4), PUSH (5), PUSH (0),


3 4 5 0 2
PUSH (2)

TOP++ for every PUSH


operation

PUSH (6) Stack overflow as all elements


are filled on the stack and
TOP++
capacity of stack is full filled.

POP( )
3 4 5 0

Peek ( ) Peek element is 0

DISPLAY () { 3, 4, 5, 0 }

B. Overflow and Underflow conditions of stack :

The overflow condition is nothing but the situation where all


elements of the stack are present so that we cannot insert more
elements onto the stack. In other words maximum size of stack
is achieved.

For example, if we have defined our stack for storing 10


elements i.e. maximum 10- PUSH operations are allowed in the
stack. If we try to PUSH 11th element onto the stack then it
creates an error during compilation of program. Therefore we
must properly code overflow condition of stack before pushing
any element onto the stack

Stack of size n

If (top == (n-1))// condition for overflow

Print “stack overflow”;

Else

//perform PUSH operation

STOP

On the other hand underflow condition is condition where stack


has no elements in it i.e. stack is empty. In case of underflow
condition we cannot POP or DISPLAY the elements from the
stack.

Stack of size n

If (top == -1)// condition for underflow

Print “stack underflow”;

Else
//perform POP or DISPLAY operation

STOP

The stack drawn below has maximum capacity =5. Top pointer
points to the 5th element. Therefore we cannot push any
element onto the stack .this is overflow condition.

3 4 5 0 2 On the other hand, stack drawn below


is empty. Hence we cannot delete the
element. This is underflow condition of stack

C. Array Implementation of STACK:

There is no in-built methods available for stack in any


programming language. However we can implement stack
either using an array or linked list. Link list and array itself are
two different data structure .we will see array implementation
of stack program first and then we will see the explanation of
each methods which is implemented in the program.in later part
we will see linked list implementation of an array.

Implementation of program
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10 // maximum array size is
initialized to 10

void PUSH();
void POP();
void DISPLAY();

int TOP=-1;// initialize stack pointer to -


1

int stack[SIZE];
int choice ,item ;

void main()// main method starts


{

clrscr();//clear the output screen

while(1)
{
printf(" *** MENU ***\n 1. PUSH\n 2. POP\n
3. DISPLAY\n 4. EXIT\n");

printf("enter your choice from menu:");


scanf("%d",&choice);

switch(choice)
{

case 1:PUSH();
break;

case 2:POP();
break;
case 3:DISPLAY();
break;

case 4:exit();

default: printf("Sorry you have entered


wrong choice\n");

}// end of switch


}// end of while

} // end of main method

void PUSH()// method which add the element


on to the stack
{

if(TOP==SIZE-1)
printf("*** stack overflow(full) ***\n");

else
{
printf("enter the item to be pushed into
the stack:");
scanf("%d",&item);
TOP++; // first increment the TOP and then
add

stack[TOP]=item; // add the element


}// end of else block

} // end of method PUSH

void POP() // method to remove TOP most


element
{
if(TOP==-1) // if stack is empty
printf("*** stack is empty ***\n");

else
{
item=stack[TOP];
TOP--;
printf("the deleted item from stack is
%d\n",item);
} // end of else block

} // end of method POP

void DISPLAY()
{

int i;
if(TOP==-1)
printf("**** stack underflow****");

else
{
printf("*** stack Display ***\n");

for(i=TOP;i>=0;i--)
printf("%d at %d\n",stack[i],i);

} // end of else block

} // end of method DISPLAY

Explanation of Program
The C implementation of a program is given below. We must
consider following points regarding to the program:
- As it is an array implementation, we must initialize our array
to maximum size (10 elements).
- The TOP pointer has to initialize to -1 ( -1 indicates that TOP
pointer initially points to nowhere)
- We must properly code main () method for our stack
implementation. Main method has switch case control
structure so that user can give his choice of operation of his
own way.
- We must code PUSH () operation of stack. PUSH operation
always checks whether stack is overflow or not. If it is in
overflow condition then it simply DISPLAYs message to the
user about overflow condition ( printf ("*** stack
overflow(full) ***\n )) otherwise it increments
TOP pointer and add the user-entered element onto the
stack. For next successive values it will add the elements
according to PUSH () function.
- In POP () function, it should check whether stack is
underflow (empty) or not. If it is empty then it simply
DISPLAYs message to the user about underflow condition
(printf("*** stack is empty ***\n”))
otherwise it simply decrements TOP pointer.
- DISPLAY () method of stack uses for loop control structure
for displaying the values of stack. Pointer i is initialized to
TOP pointer and it decrements till 0th value of an array. After
every iteration of for loop it DISPLAYs the result to the user.
We can also initialize I pointer to 0th element which
increments to its maximum TOP pointer to display the
elements of the stack. Both this implementations are
correct.
- We can also code PEEK () function that will return the
highest element of the stack. We just have to display the
current element of stack where the TOP pointer is pointed.

Output of program
output:

*** MENU ***


1. PUSH
2. POP
3. DISPLAY
4. EXIT
enter your choice from menu:1
enter the item to be pushed into the
stack:10
*** MENU ***
1. PUSH
2. POP
3. DISPLAY
4. EXIT
enter your choice from menu:1
enter the item to be pushed into the
stack:20
*** MENU ***
1. PUSH
2. POP
3. DISPLAY
4. EXIT
enter your choice from menu:1
enter the item to be pushed into the
stack:30
*** MENU ***
1. PUSH
2. POP
3. DISPLAY
4. EXIT
enter your choice from menu:4

D. Implementation of two STACKS in array:


In this case an array can be used to implement two stacks i.e.
one from right end and other from left end. As shown in the
figure below.

25 64 67 9

TOP 1 TOP 2

Implementation of program:

The program makes use of one long size array to implement two
stacks viz. stack 1 and stack 2. They have individual methods like
PUSH1 (), POP1 (), DISPLAY1 () for stack 1 and PUSH2 (), POP2 (),
DISPLAY2 () for stack 2 respectively.

#include<stdio.h>
#include<stdlib.h>

void main()
{
Int TOP1, TOP2; // stack 1 and stack 2
pointers
int n, choice=1,a,i;
int stack[100];
printf("Enter size of array you want to
use\n");

scanf("%d",&n);
TOP1=-1; // initialize stack 1 pointer to
extreme left
TOP2=n; // initialize stack 2 pointer to
extreme right
while(choice!=0)
{
printf("***** What do u want to do? *****
\n");
printf("1.PUSH element in stack 1\n");
printf("2.PUSH element in stack 2\n");
printf("3.POP element from stack 1\n");
printf("4.POP element from stack 2\n");
printf("5.DISPLAY elements of stack 1\n");
printf("6.DISPLAY elements of stack 2\n");
printf("0.EXIT from main menu \n");
scanf("%d",&choice);

switch(choice)
{

case 1: // case 1 starts


{

if(TOP1==(TOP2-1))
printf(" stack 1 Overflow\n");

else
{
printf("Enter the element to enter on to
the stack 1 \n");
scanf("%d",&a);
TOP1++;
stack [TOP1]=a;
} // end else block
break;
} // end case 1

case 2: // case 2 starts


{
if(TOP2==(TOP1+1))
printf(" stack 1 Overflow\n");

else
{
printf("Enter the element to enter on to
the stack 2 \n");
scanf("%d",&a);
TOP2--
stack [TOP2]=a;
} // end of else block
break;
}// end of case 2

case 3: // case 3 starts


{

if(TOP1==-1)
printf("Stack 1 is empty\n");

else
{
TOP1--;
a= stack[TOP1];
printf("%d\n",a);
} //end of else block

break;
} // end of case 3

case 4: // case 4 starts


{
if(TOP2==n)
printf("Stack2 is empty\n");
else
{
TOP2++;
a= stack[TOP2];
printf("%d\n",a);
} //end of else block

break;
} // end of case 4

case 5: // case 5 starts


{

if(TOP1==-1)
printf("Stack 1 is empty\n");

else
{
printf("Stack 1 is \n");
for(i=0;i<=TOP1;i++)
printf("%d ", stack[i]);
printf("\n");
} // end of else block

break;
} // end of case 4

case 6:
{
if(TOP2==n)
printf("Stack 2 is empty\n");

else
{
printf("Stack 2 is-->>\n");
for(i=(n-1);i>=TOP2;i--)
printf("%d ", stack[i]);
printf("\n");
} // end of else block

break;
} // end of case 6

case 0:
break;

} // end of switch

} // end of while
} // end of main method

Explanation of program:

- As it is an array implementation, we must initialize our array


to maximum size (100 elements )

For stack 1: (Case 1, 3, 5 in switch case)

- The TOP 1 pointer initialized to -1 for stack 1( -1 indicates


that TOP pointer initially points to nowhere)
- PUSH 1 () [case 1] operation of stack 1 is similar to normal
array implementation of stack. PUSH operation always
checks whether stack is overflow or not. If it is in overflow
condition then it simply DISPLAYs message to the user about
overflow condition (printf("stack 1
Overflow\n")) otherwise it increments TOP pointer and
add the user-entered element onto the stack.
- In POP 1() [case 3] function, it should check whether stack 1
is underflow (empty) or not. If it is empty then it simply
displays message to the user about underflow condition (
printf("*** stack 1 is empty ***\n”))
otherwise it simply decrements TOP pointer.
- DISPLAY 1 () [case 5] method of stack 1 uses for loop control
structure for displaying the values of stack. Pointer i is
initialize to 0 to TOP 1 pointer. After every iteration of for-
loop pointer i is incremented and it displays the result to the
user.

For stack 2: (Case 2, 4, 6 in switch case)

- The TOP 2 pointer has to initialize to ‘n’ for stack 2( n


indicates that TOP pointer initially points to nowhere)
- PUSH 2() [ case 2 ] operation of stack 2 always checks
whether stack 2 is overflow or not. If it is in overflow
condition then it simply DISPLAYs message to the user about
overflow condition (printf(" stack 2
Overflow\n")) otherwise it decrements TOP pointer
and add the user-entered element onto the stack 2.
- In POP 2 () [ case 4] function , it should check whether
stack is underflow ( empty) or not. If it is empty then it
simply DISPLAYs message to the user about underflow
condition (printf("*** stack 2 is empty
***\n”)) otherwise it simply increments TOP pointer.
- DISPLAY 2() [case 6] method of stack uses for loop control
structure for displaying the values of stack. Pointer i is
initialize to (n-1) to TOP 2 pointer. After every iteration of
for- loop it DISPLAYs the result to the user.

output of program :

***** What do u want to do? *****


1.PUSH element in stack 1
2.PUSH element in stack 2
3.POP element from stack 1
4.POP element from stack 2
5.DISPLAY elements of stack 1
6.DISPLAY elements of stack 2
0.EXIT from main menu
1
Enter the element to enter on to the stack
1
23
***** What do u want to do? *****
1.PUSH element in stack 1
2.PUSH element in stack 2
3.POP element from stack 1
4.POP element from stack 2
5.DISPLAY elements of stack 1
6.DISPLAY elements of stack 2
0.EXIT from main menu
2
Enter the element to enter on to the stack
2
36
***** What do u want to do? *****
1.PUSH element in stack 1
2.PUSH element in stack 2
3.POP element from stack 1
4.POP element from stack 2
5.DISPLAY elements of stack 1
6.DISPLAY elements of stack 2
0.EXIT from main menu
3
***** What do u want to do? *****
1.PUSH element in stack 1
2.PUSH element in stack 2
3.POP element from stack 1
4.POP element from stack 2
5.DISPLAY elements of stack 1
6.DISPLAY elements of stack 2
0.EXIT from main menu
5
Stack 1 is empty
***** What do u want to do? *****
1.PUSH element in stack 1
2.PUSH element in stack 2
3.POP element from stack 1
4.POP element from stack 2
5.DISPLAY elements of stack 1
6.DISPLAY elements of stack 2
0.EXIT from main menu
0

E. Applications of STACK :

Applications of Stack are as follows:

 Recursion: In recursion stack is heavily used. The status of


function gets stored on the stack before going for the next
call. ( we will see the working in next topic )
 Stack can be used to check the continuity of parenthesis.
 Stack can be used to convert numbers from one number
system to another number system like Binary to
Hexadecimal etc.
 It can be used to check whether the string is palindrome OR
not.
 Stack is also used for evaluating postfix expressions. ( we will
see the working in next topic )
 Stack can be used for expression conversion like Infix to
Postfix. Etc. ( we will see the working in next topic )
Infix  A+B (Operator is in middle)
Postfix  AB+ (Operator is at right end)
Prefix  +AB (Operator is at left end)

The utility of above expressions can be used in system


programming .The operations are stored in postfix form in the
memory which gets decompiled by compiler during execution of
ASSEMBLY program.

F. Infix , Postfix , Prefix Expressions : (Polish Notations)


 Infix Expression :

An expression where the operators are placed in the middle of


the operands is called as Infix Expression.

For Example. 2+3*5 .The Infix expression can be converted into


prefix and postfix using stack as a data structure.

 Postfix Expression :

An expression where the operators are placed after the


operands is called as Postfix Expression.

For Example . 235*+

 Prefix Expression :

An expression where the operators are placed before the


operands is called as Prefix Expression.

For Example . +2*35

1. Converting Infix to Postfix expression :


Create three stacks namely infix [], stack [] , postfix [].
Infix [] stack stores the input expression. Postfix stack stores
output expression and stack [] stores all operators with their
precedence.
STEP 1: For a given Infix Expression we must scan string from
left to right .Stack must be initialized to empty.

STEP 2: There are two possibilities:


- If the scanned character is operand, add it to the postfix
String directly.

- If the scanned character is operator, Then

If Stack is Empty. If Stack is not empty

PUSH the stack character in the Compare the precedence of


Stack directly. Operator with the stack top

Stack TOP is higher precedence Stack TOP is lower precedence

POP the stack with remaining PUSH the operator to the stack
Operator using LIFO manner.
STEP 3: Repeat STEP 2 till all characters are scanned.

STEP 4: If the Stack TOP is not empty, then finally POP all
operators & make the stack empty.

Example:

Let us illustrate the example for converting infix to postfix


expression.

The infix expression is: a + b * c - d

Step 1: we must scan the expression from left to right.

The first character is ‘a’ which is an operand, therefore we must


directly add to postfix [] string:

( postfix )

Step 2 : next character is ‘+’ which is operator. And initially stack


[] is empty therefore we must add operator directly onto the
stack

( stack )

Step 3 : next character is ‘ b’ which is operator and therefore we


must directly add to postfix [] stack .

a b
( postfix )

Step 4 : next character is ‘*’ which is operator and stack [] is not


empty as there is one operator in it. Therefore we must
compare the precedence of * operator with + operator in stack.
* has higher precedence therefore we will add directly onto the
stack.

+ *

(stack )

Step 5 : next character is c , we will directly add it onto the


postfix []

a b c

(postfix)

Step 6 : next character is - . and stack [] is not empty as there


are 2 operators preset in it. Therefore we must compare the
precedence of – operator with stack top operator i.e. * .

“ – “ has lower precedence . Therefore we POP the * and push


onto the postfix.

a b c *

( postfix )
We will compare the precedence of ‘– ‘with stack top operator
i.e. ‘+ ‘. Both has same precedence. Therefore our – operator
must be pushed to stack []

+ -

(stack)

Step 7 : scan the next character i.e. d which is an operand . we


must directly add it onto postfix .

a b c * d

(postfix)

Step 8 : now all characters are scanned . stack[] is not empty


therefore we must POP all characters of stack [] onto postfix [] .

a b c * d - +

(Postfix)

Postfix [] will hold the postfix expression of given infix


expression .

Implementation of program:

#include<stdio.h>

#include<stdlib.h>

void readinfix();

void compute() ;

void DISPLAY() ;
char infix[100],postfix[100],stack[100];

int n,TOP,i,j;

printf(" Enter the array Size :");

scanf("%d",&n);

TOP=-1;

i=-1;

j=-1;

void readinfix()

char p;

printf("Enter the infix string :");

gets(infix);

while (infix[i] != '\0')

i++;

void compute()

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

if(isoperand(infix[i]))

j=j+1;

postfix[j]=infix[i];

else

if(TOP==-1)

TOP=TOP+1;

stack[TOP]=infix[i];

else

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

while(stack[TOP]!='(')

j=j+1;

postfix[i]=stack[TOP];
TOP=TOP-1;

TOP=TOP-1;

else

if(priority(infix[i])>
priority(stack[TOP]))

TOP=TOP+1;

stack[TOP]=infix[i];

else

while((priority(infix[i])<=
priority(stack[TOP])) && TOP!=-1 &&
stack[TOP]!='(' && infix[i]!='(')

j=j+1;

postfix[j]=stack[TOP];

TOP=TOP-1;

if(TOP==-1)
break;

TOP=TOP+1;

stack[TOP]=infix[i];

while(TOP!=-1)

j=j+1;

postfix[j]=stack[TOP];

TOP=TOP-1;

}// end of method

boolean isoperand(char x)

if((x>='a' && x<='z')||(x>='A' && x<='Z')||


(x>=0 && x<=9))

return true;

else
return false;

int priority(char ch)

if(ch== ')')

return 4;

if((ch=='*')||(ch=='/'))

return 3;

if((ch=='+')||(ch=='-'))

return 2;

if((ch=='<')||(ch=='>'))

return 1;

return 0;

void DISPLAY()

printf("POSTFIX EXPRESSION : ");

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

printf(postfix[i]);

}
void main ()

clrscr();

readinfix();

compute();

DISPLAY();

Explanation of program:

Regarding to the program we must focus on following points:

- We must create character array infix [100], postfix [100],


stack [100] with initialization of their pointer i, j and TOP. All
pointer should be initialized to -1. All these character array
will be acting as stack data structure.
- readinfix () method accepts infix string from user and stored
in infix[] array.
- Compute () method will actually perform conversion of infix
to postfix string.
- DISPLAY() method will print output string
- isoperand() method is a Boolean method that will return
value true ( 1) if scanned character is operand. And result is
given to compute() method
- priority () method will assign the priority to the operator .
For example ‘ / ‘ has a highest priority than ‘+’ operator .

Output of program :
Enter the array Size :

10

Enter the infix string :

2+3*5

POSTFIX EXPRESSION :

235*+

2. Evaluating Postfix Expression :

STEP 1 : Scan the postfix string from left to right & Initialize the
stack .

STEP 2 : There are two possibilities :

- If the scanned character is operand, add to it to stack.


- If the scanned character is an operator, there will be at least
two operand in the stack. If the scanned character is an
operator then POP two topmost elements in stack and apply
operator between them & PUSH the result to stack.

STEP 3: Repeat STEP 2 till all characters are scanned.

STEP 4: Finally we will be with last element on the stack, that


value is the Postfix value of the expression.

#include<stdio.h>

#include<stdlib.h>

void readpostfix();
void compute();

char postfix[100];

int stack[100];

int i,a,b,c,TOP,n;

printf("Enter the array size :");

scanf("%d",&n);

TOP=-1;

i=-1;

void readpostfix()

char p;

printf("Enter the infix string :");

gets(infix);

while (infix[i] != '\0')

i++;

boolean isoperand(char c)

{
if((c>='0')&&(c<='9'))

return true;

else

return false;

void compute()

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

if(isoperand(postfix[i]))

TOP++;

stack[TOP]=(int)(postfix[i]-'0');

else

a=stack[TOP];

TOP--;

b=stack[TOP];

switch(postfix[i])

{
case '+' : c=b+a;

stack[TOP]=c;

break;

case '-' : c=b-a;

stack[TOP]=c;

break;

case '*' : c=b*a;

stack[TOP]=c;

break;

case '/' : c=b/a;

stack[TOP]=c;

break;

default : printf("INVALID OPERATOR");

}// end else part

printf("VALUE OF THE EXPRESSON IS:"+


stack[TOP]);

void main()

{
readpostfix();

compute();

Explanation of a program :

Regarding to the program we must focus on following points:

- We must create character array postfix [100], stack [100]


with initialization of their pointer i and TOP. All pointer
should be initialized to -1 . All these character array will be
acting as stack data structure.
- readpostfix() method accepts infix string from user and
stored in postfix[] array.
- Compute () method will actually perform conversion of infix
to postfix string.
- DISPLAY () method will print the value of postfix string.
- isoperand() method is a Boolean method that will return
value true ( 1) if scanned character is operand. And result is
given to compute () method.

Output of a program :

Enter the array size :

10

Enter the infix string :

235*+
VALUE OF THE EXPRESSON IS

21

G. Recursion: an application of STACK :

As we know Recursion is nothing but a function which calls itself


until terminating condition becomes true.

However in recursion when function calls itself, the execution of


parent function is suspended (stopped for some time). Say for
example function F () is a recursive function. In first pass, when
function calls itself (say call F1 ()) the previous pass F (which is a
parent pass) need to store somewhere in the memory because
execution of F is not yet completed. Similarly in subsequent
passes we need to store previous passes of same function.

The central question is who stores all these passes? Obviously


we require some data structure to store all these passes.

The answer is STACK!

Working of stack in case of recursion:

Every executable main is loaded into a program stack at the


beginning of execution. It remains there until it completes, at
which time it is popped off of the stack.
If main calls a function, that function is loaded onto the TOP of
the stack and remains there until it is complete at which point it
is popped off of the stack.

Now, a recursive function calls itself. That means another


instance of the function will be placed on the stack and will
remain there until the function completes.
You need to look at a recursive function in terms of the program
stack. Let’s use factorial as an example. 5 factorial is 5 * 4 * 3 *
2 * 1 = 120 and this can be implemented recursively.

int f (int x)
{
if(x == 1) return 1;
return f(x-1)*x;
}
void main()
{
int y = f(5);// main call
// y should get 120
}

Main calls the function f with a value of 5, so on the stack we


get f(5). Line 1 is false so we go to line 2 which calls f(4), etc.
Note that f(4) must complete before f(5) can complete. f(5) will
complete by returning 5*f(4). The stack will look like:
So at this point none of the functions have yet returned! The
first to return will be f(1) which will return 1. Then f (2) will
return 2. Then f(3) will return 6. As shown in fig.
H. Linked Representation of stack :

As I have mentioned earlier, Stack implementation can be done


in two ways. Viz. array and linked list. Linked list implementation
of stack is quite difficult as we are going to deal with pointers.
We will see this topic in “linked list” part of this subject. It is
inappropriate to learn this topic right now as we don’t know
what the linked list is.

You might also like