You are on page 1of 43

I B Tech II Semester CSE (R-20)

DATA STRUCTURES

STACKS
***************************************************************************
Stacks: Introduction to Stacks,
Array Representation of Stacks, Operations on Stacks,
Linked list Representation of Stacks, Operations on Linked Stack.

Applications of stacks : Reversing list,


Factorial Calculation,
Infix to Postfix Conversion,
Evaluating Postfix Expressions.
***************************************************************************
STACK
Definition: A Stack is an ordered collection of data items, into which new items may be
inserted and from which items may be deleted at one end called Top of the Stack.

The most important thing is that the last element inserted into the stack is the first element
deleted. For this reason a stack is sometimes called as LIFO (Last In First Out) list.

6
5
4
3 D TOP
2 C
1 B
0 A

STACK

Unlike an array stack provides the insertion and deletion of items. So a stack is a
dynamic, constantly changing object. New items may be put on top of the stack or items
which are at the top of the stack may be removed.

The two changes which can be made to a stack are given special names, those are
PUSH and POP. When an item is added to a stack it is pushed onto the stack and when an
item is removed it is popped from the stack.

Although an array cannot be a stack it can be the home of the stack i.e., an array can
be declared with a range that is large enough for the maximum size of the stack. During the
course of program execution the stack will grow and shrink within the space reserved for it.
One end of the array will be fixed bottom of the stack while the top of the stack will
constantly shift as items are popped and pushed. Thus another field is needed to keep track of
the current position of the top of the stack.

So stack is a variable which is a collection of two members


1) an array to hold values
2) top to hold position of top most element in the stack
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 1 of 43
Figure shows pushing of data items on to the stack.

Figure shows popping of data items from the stack.

A Stack in “C” may be declared as a structure containing two members. An array to


hold the elements of the stack and an integer to indicate the position of the current stack top
within the array.

#define MAXSTACK 50 Type declaration


struct stack
{
int entry[MAXSTACK];
int top;
};
typedef struct stack stacktype;

stacktype s; Variable Declaration


int x;

Given a stack s and an item x, performing the operation push(s, x) adds the item x to the
top of the stack S.
push(s, x)

Similarly the operation pop(s) removes the top element and returns it as a function value.

X = pop(s);
This assignment operation removes the element from the top of the stack S and assigns its
value to x.

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 2 of 43
PUSH
Inserting / adding an element to a stack is called push. While pushing a
value x into stack top is increased by 1 and element x will be placed in the
position of top. For example if x is the element to be placed on stack we use
the following two statements

top = top+1;
entry[top]= x;

We normally consider s as a stack. s is a structure variable. s is the


combination of entry and top. entry is array. top is the position of top most
element in the stack. To push x to stack we write the two statements as
follows.

s.top = s.top + 1;
s.entry[s.top] = x;

If we consider s as pointer to structure then the two


statements will be written as

s->top = s->top + 1;
s->entry[s->top] = x;

In the main function we used to call function push to insert


one element to stack. To keep the modification we used to call
the function through reference parameters.

push(&s,x);

s is structure of stack and &s is being passed as reference


parameter to the function push. and the members of stack can
be accessed through -> arrow operator.

Function to push an element into a stack

void push (s,x)


stacktype *s;
int x;
{
if ( s->top == MAXSTACK – 1)
printf (“Error – Stack Overflow \n”);
else
{
s->top = s->top+1;
s->entry[s->top] = x;
}
}

To push an element to stack, it should have some free space.


If top is equal to MAXSTACK-1 means stack is full. If stack is
full pushing an element is not possible. An error message
“stack overflow” will be displayed. If stack is not full, top
will be increased by 1 and element will be placed on top of
stack.

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 3 of 43
POP
Deleting an element from stack is called pop. Top most element from the
stack will be deleted. After deleting the element from top of the stack top
position will be reduced by one. consider entry is an array to store elements
and top is a variable to hold position of recent element placed on the stack
we use the following two statements to remove one element from the stack.

x = entry[top];
top = top – 1;

we normally consider s as a stack. s is a structure variable. s is the


combination of entry and top. entry is an array to hold elements of stack.
top is a variable to hold the position of top most element in the stack. To pop
an element from the stack we write the two statements as follows.

x = s.entry[s.top];
s.top = s.top – 1;

if we consider s as pointer to structure variable stack then the two


statement will be written as

x = s->entry[s->top];
s->top = s->top – 1;

the members of pointer structure are accessed through ->.


in the main function we used to call function pop to remove one element
from the stack. To keep the modification we used to call the function
through reference parameters.

x = pop(&s);

s is structure of stack being passed as reference parameter to the function


pop and the members can be accessed through -> arrow operator.

Function to pop an element from a stack

int pop(s)
stacktype *s;
{
int x;
if (s->top == -1)
printf(“Error – Stack Underflow\n”);
else
{
x = s->entry[s->top];
s->top = s->top – 1;
return(x);
}
}
To remove elements stack should contain elements. If there are
no elements in the stack top will have value -1. If top is -1
there are no elements to remove from the stack, that is stack
empty. If stack is not empty then only we can remove an
element from stack.
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 4 of 43
Example: Consider S is a stack which can store a maximum of 5 values. Let us apply push
and pop operations one by one. Initially stack S is empty. There are no elements in the stack
S. When there are no elements top = -1.

4
3 s.top = -1;
Initialization of 2 Top = -1
stack 1
0
Empty stack

push(S,10) : Initially stack S is empty. top is -1. Now attempting to push an element 10 to
the stack S. push(S,10) means insert 10 in the stack S. While inserting an element top will be
increased by 1. So top = -1+1=0. Element 10 will be placed in top location i.e. at location 0 in
the stack S.
s.top = 0;
s.entry[0] = 10;

4 s.top=s.top+1;
3 s.entry[s.top]=x;
push (s,10) 2
1
0 10 Top
S
push(s,20) : Now stack S contains one element. top is 0. Now attempting to push an
element 20 to the stack S. push(S,20) means insert 20 in the stack S. While inserting an
element top will be increased by 1. So top = 0+1=1. Element 20 will be placed in top location
i.e. at location 1 in the stack.
s.top = 1;
s.entry[1] = 20;

4
s.top=s.top+1;
3
push(s,20) 2
s.entry[s.top]=x;
1 20 Top
0 10
S
push(S,30) : Now stack S contains two elements. top is 1. Now attempting to push an
element 30 to the stack S. push(S,30) means insert 30 in the stack S. While inserting an
element top will be increased by 1. So top = 1+1=2. Element 30 will be placed in top location
i.e. at location 2 in the stack. s.top = 2;
s.entry[2] = 30;

4 s.top=s.top+1;
push(s,30) 3 s.entry[s.top]=x;
2 30 Top
1 20
0 10
S

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 5 of 43
push(S,40) : Now stack S contains three elements. top is 2. Now attempting to push an
element 40 to the stack S. push(S,40) means insert 40 in the stack S. While inserting an
element top will be increased by 1. So top = 2+1=3. Element 40 will be placed in top location
i.e. at location 3 in the stack.
s.top = 3;
s.entry[3] = 40;

4 s.top=s.top+1;
push(s,40) 3 40 Top s.entry[s.top]=x;
2 30
1 20
0 10
S

push(S,50) : Now stack S contains four elements. top is 3. Now attempting to push an
element 50 to the stack S. push(S,50) means insert 50 in the stack S. While inserting an
element top will be increased by 1. So top = 3+1=4. Element 50 will be placed in top location
i.e. at location 4 in the stack.
s.top = 4;
s.entry[4] = 50;
s.top=s.top+1;
push(s,50)
4 50 Top s.entry[s.top]=x;
3 40
2 30
1 20
0 10
S
Here in this example the stack can store a maximum of 5 elements. The last element is at
location 4. top reached its maximum position so stack is full.

Now attempting to add one more element to stack i.e. applying push(S, 60) resulting into
overflow. If stack is having some free space we can accommodate value 60 in the stack. But
stack is full. So the value 60 we are attempting to push will not be pushed or inserted onto the
stack and resulting to an error condition “stack overflow”. top remain as 4. Last element
remains as 50.

push(s,60) 4 50 Top
3 40
2 30 Stack full
1 20 overflow condition
0 10
S

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 6 of 43
Now try to remove / delete elements from stack one by one. Deleting an item from stack is
said to be pop operation. The stack contains 5 elements. top pointing to 4 th element. top=4.

4 50 Top
3 40
2 30
1 20
0 10

x = pop(s) S
Applying pop operation deletes an item from the stack from top location. top is 4 the top
element is 50. The element 50 is removed from the stack. The value of top decreased by 1.
So, top becomes 3. x=s.entry[s.top]; x = 50
s.top=s.top-1; top=3

4
3 40 Top
2 30
1 20
0 10

x = pop(s) S
Applying pop operation deletes an item from the stack from top location. top is 3 the top
element is 40. The element 40 is removed from the stack. The value of top decreased by 1.
So, top becomes 2. x=s.entry[s.top]; x = 40
s.top=s.top-1; top=2

4
3
2 30 Top
1 20
0 10

x = pop(s) S
Applying pop operation deletes an item from the stack from top location. top is 2 the top
element is 30. The element 30 is removed from the stack. The value of top decreased by 1.
So, top becomes 1. x=s.entry[s.top]; x = 30
s.top=s.top-1; top=1
4
3
2
1 20 Top
0 10

x = pop(s) S
Applying pop operation deletes an item from the stack from top location. top is 1 the top
element is 20. The element 20 is removed from the stack. The value of top decreased by 1.
So, top becomes 0. x=s.entry[s.top]; x = 20
s.top=s.top-1; top=0
4
3
2
1
0 10 Top
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 7 of 43
x = pop(s)
Still there is one more element in the stack. Applying pop operation deletes an item from the
stack from top location. top is 0 the top element is 10. The element 10 is removed from the
stack. The value of top decreased by 1. So, top becomes -1. removing the only item makes
stack empty and top becomes -1. x=s.entry[s.top]; x = 10
s.top=s.top-1; top=-1

4
3
2 Top = -1
1
0
Empty Stack
x = pop(s)
Now there are no elements in the stack. Applying pop operation attempts to delete an item
from the stack from top location. As there are no elements it is not possible to delete item
from stack which results into a condition “stack underflow”. Stack remains empty and top
remains as -1.

4
3
2 Top = -1
1
0
Empty Stack
At each point, the top element is removed, since a deletion can be made at only from
the top. The most important thing is that the last element inserted into the stack is the first
element deleted. For this reason a stack is some times called as LIFO (Last In First Out)
list.

A helpful analogy is to think of a stack of trays or of plates sitting on a counter in a


busy cafeteria. Though out the lunch hour customers take trays off the top of the stack, and
the employees place returned trays back on top of the stack. The tray most recently put on the
stack is the first one taken off. The bottom tray is the first one put on, and the last one to be
used.

#define MAXSTACK 50 Type declaration


struct stack
{
int entry[MAXSTACK];
int top;
};
typedef struct stack stacktype;

stacktype s; Variable Declaration


int x;

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 8 of 43
Function to display the elements of stack

void liststack(s)
stacktype s;
{
int i;
for (i=0; i<=s.top; i++)
printf( “%d\n”, s.entry[i]);
printf (“\n”);
}

This function displays all the elements of stack. The elements


are stored from index 0 to top. All the elements will be
printed from 0 to top position. By using this function we are
not modifying the stack. So there is no need to pass the
parameter as reference parameter. simply the stack parameter
is passed to the function as value parameter. The members are
accessed through “.” dot operator as
s.top and
s.entry[i]

Function to determine whether a stack is empty or not

int empty(s)
stacktype s;
{
if (s.top == -1)
return(1);
else
return(0);
}

To check whether the stack is empty or not, we can use this


function. If top is -1 we can say the stack is empty. This
function returns 1 if top is -1 i.e. the stack is empty. If
stack is not empty the function returns 0. By executing this
function we are not modifying contents of stack. So, the
parameters are passed as value parameters only. That’s why we
use “.” dot operator to access members of structure s.

s.top

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 9 of 43
/*----------------------stack.c----------------------------
Program to implement a stack
-----------------------------------------------------------*/
#include <stdio.h>
#include <conio.h>
#define MAXSTACK 50

struct stack
{
int entry[MAXSTACK];
int top;
};
typedef struct stack stacktype;

void push(s,x)
stacktype *s;
int x;
{
if ( s->top == MAXSTACK – 1)
printf (“Error – Stack Overflow \n”);
else
{
s->top = s->top + 1;
s->entry[s->top] = x;
}
}

int pop(s)
stacktype *s;
{
int x;
if (s->top == -1)
{
printf(“Error – Stack Underflow\n”);
return -1;
}
else
{
x = s->entry[s->top];
s->top = s->top–1;
return(x);
}
}

void liststack(s)
stacktype s;
{
int i;
for(i=0; i <=s.top; i++)
printf( “%d\n”, s.entry[i]);

printf (“\n”);
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 10 of 43
int empty(s)
stacktype s;
{
if (s.top == -1)
return(1);
else
return(0);
}

void main()
{
stacktype s;
int x, opt;

s.top = -1; /*-------- initialization of stack */


clrscr();

do
{
printf(“\n Operations of stack \n”);
printf(“ 1. PUSH \n”);
printf(“ 2. POP \n”);
printf(“ 3. LIST \n”);
printf(“ 4. EXIT \n”);
printf(“ Enter your option: \n”);
scanf(“%d”, &opt);

switch (opt)
{
case 1: printf(“Enter x”);
scanf(“%d”, &x);
push (&s,x);
break;

case 2: if (empty(s)==1)
printf(“Error-Stack is Empty”);
else
{
x = pop (&s);
printf(“popped element %d”, x);
}
break;

case 3: printf(“The elements of stack\n”);


liststack(s);
break;
} /* -------end of switch */

} while (opt <= 3); /*------- end of do loop */

getch();
} /*------- end of Main */

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 11 of 43
While calling functions push() and pop() we are using call by reference technique. Usually a
function returns only one value through return statement.
push(&s,x);
x=pop(&s);
While pushing an element top value will be increased by one and one element will be added
to stack. If we use reference parameter as formal parameter, whatever the changes that
occurred to the stack in the function they reflect in the calling function also. In push and pop
functions stack parameter is taken as reference parameter, because we are modifying the
contents of stack.

In liststack() function we are just displaying the contents of the stack. We are not modifying
the content of stack. So we have taken the parameter as a value parameter.

OUTPUT
Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 1
enter x : 10

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 1
enter x: 20

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 1
enter x: 30

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 3
The elements of STACK
10 20 30

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 2
popped element = 30

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 12 of 43
Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 3
The elements of STACK
10 20

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 1
enter x: 50

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 3
The elements of STACK
10 20 50

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 1
enter x: 60

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 3
The elements of STACK
10 20 50 60

Operations of Stack
1 PUSH
2 POP
3 LIST
4 EXIT
enter your option : 4

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 13 of 43
********************************************************************
Application of Stack :: Reversing list
********************************************************************
Suppose if we have an array of elements and are asked to rearrange the elements in
reverse fashion in the same array. Assume that the array can store 5 elements as
follows,

After reversing the elements the array a contains the following elements.

We use stack to reverse a list. Initially declare a stack to accommodate all the elements
of array. size of stack to store all the elements of array.

push elements of array one by one on to the stack.


now pop from stack and store in the same array from index 0.
by the time the stack is empty the array contains elements in reverse order.

Explanation of the procedure using diagrams


All the array values are pushed on to the stack one by one. declare a stack to store all the 5
elements of array.

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 14 of 43
pop stack and store the element in the array till stack is empty

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 15 of 43
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 16 of 43
/* ---revlist.c--------Program to reverse a list using stack----------*/
#include <stdio.h>
#include <conio.h>
#define MAXSTACK 50
struct stack
{
int entry[MAXSTACK];
int top;
};
typedef struct stack stacktype;

void push(s,x)
stacktype *s;
int x;
{
if ( s->top == MAXSTACK - 1)
printf("Error: Stack Overflow \n");
else
{
s->top = s->top+1;
s->entry[s->top] = x;
}
}
int pop(s)
stacktype *s;
{
int x;
x = s->entry[s->top];

s->top = s->top-1;
return(x);
}
void main()
{
stacktype s;
int x, opt;
int a[10],i,n;

clrscr();
printf("enter n");
scanf("%d",&n);
printf("enter array elements \n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);

s.top = -1; /*------- initialization of stack */


for (i=0;i<n;i++)
push(&s,a[i]);

for(i=0;i<n;i++)
a[i]=pop(&s);

printf(" the list elements are\n");


for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 17 of 43
OUTPUT
enter n
5
enter array elements
10 20 30 40 50
the list of elements are
50 40 30 20 10

***********************************************************
Application of Stack :: Finding Factorial using stack
***********************************************************
Factorial of any value is the product of all numbers ranging from 1 to itself.

To find factorial of 4 we have to multiply 1, 2, 3 and 4. So first push all numbers from 4 to 1
on to a stack.

scanf(“%d”,&n);
top=-1;
while (n>0)
{
push(&s,n);
n=n-1;
}

After pushing all values on to the stack, pop numbers one by one and get product till
stack is empty as shown below.

fn = 1;

while(s.top!=-1)
{
x = pop(&s);
fn = fn*x;
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 18 of 43
The final product is 24 which is factorial of 4.

/*-------------------factstk.c------------------------------
Program to find factorial of n using stack
-----------------------------------------------------------*/
#include <stdio.h>
#include <conio.h>
#define MAXSTACK 50

struct stack
{
int entry[MAXSTACK];
int top;
};
typedef struct stack stacktype;

void push(s,x)
stacktype *s;
int x;
{
if(s->top == MAXSTACK - 1)
printf("Error : Stack Overflow \n");
else
{
s->top = s->top+1;
s->entry[s->top] = x;
}
}
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 19 of 43
int pop(s)
stacktype *s;
{
int x;

x = s->entry[s->top];
s->top = s->top-1;
return(x);
}

void main()
{
stacktype s;
int x, opt;
int n,fn;

clrscr();

printf("enter n");
scanf("%d",&n);

s.top = -1; /*-------- initialization of stack */

while (n>0)
{
push(&s,n);
n--;
}

fn=1;

while(s.top!=-1)
{
x=pop(&s);
fn=fn*x;
}

printf("factorial = %d \n",fn);

getch();
}

OUTPUT
enter n
4
factorial = 24

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 20 of 43
POLISH NOTATION
Operators Priority
 6
* / % 5
+ - 4
== != 3
< <= > >= 2
&& || 1
= 0

The method of writing all operators either before their operands, or after them is
called Polish Notation. When the operators are written before their operands, it is called
prefix form. When the operators come after their operands, it is called the postfix form or
some times reverse polish form or suffix form. Writing operators between operands is called
the usual infix form.

A*B Infix A+B*C Infix


* AB Prefix ABC *+ Postfix
AB * Postfix +A*BC Prefix

Infix, Postfix and Prefix:

Consider the sum of A and B. We think of applying the operator “+” to the operands
A and B and write the sum as A+B. This particular representation is called Infix. There are
two alternate notations for expressing the sum of A and B, using the symbols A, B and +.
These are
+AB Prefix
AB+ Postfix.

The prefix, infix and postfix refer to the relative position of the operator with respect
to the two operands. In prefix notation the operator precedes the two operands, in postfix
notation the operator follows the two operands, and in infix notation the operator is in
between the two operands.

Let us now consider some additional example. The evaluation of example A+B*C, as
written in standard infix notation, requires knowledge of which of the two operations, + or *
we know that multiplication is to be done before addition. We say that multiplication takes
precedence over addition. Suppose we want to rewrite A+B*C in postfix. Applying the rules
of precedence, we first convert the portion of the expression that is evaluated first, namely the
multiplication. By doing this conversion in stages we obtain
A+B*C
A + (B * C)
A + (BC *)
ABC * +  Postfix form.

The only rules to remember during the conversion process are that operations with
highest precedence are converted first and that after a portion of the expression has been
converted to postfix it is to be treated as a single operand. Consider the same example with
parentheses as shown.
(A+B)*C  Infix
(A B + ) * C
(A B + ) C *
AB+C*  Postfix
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 21 of 43
In this example the addition is converted before the multiplication because of the
parentheses.

We consider five binary operations : addition, subtraction, multiplication, division and


exponentiation. The order of precedence of these operators from highest to lowest is as
follows.

Exponentiation
Multiplication / Division
Addition / Subtraction.

When unparenthesized operators of the same precedence are scanned, the order is
assumed to be left to right except in the case of exponentiation where the oder is assumed to
be from right to left. Thus

A+B+C means (A + B ) + C where as


A$ B$ C means A$ ( B$C)

Infix Postfix
A+B AB+
A+B–C AB+C–
(A+B)*(C–D) AB+CD–*
A $ B * C – D + E / F / (G + H ) AB$C*D–EF/GH+/+
(( A + B ) * C – ( D – E )) $ (F + G ) AB+C*DE- -FG+$
A – B / ( C * D$ E ) ABCDE$*/-

The precedence rules for converting an expression from infix to prefix are identical.
The only change from postfix conversion is that the operator is placed before the operands
rather than after them.

Infix Prefix
A+B +AB
A+B–C –+ABC
(A+B)*(C–D) *+AB–CD

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 22 of 43
Evaluating a postfix expression:
Each operator in a postfix string refers to the previous two operands
in the strings. Suppose that each time we read an operand we push it on to
a stack. When we reach an operator, its operands will be the top two
elements on the stack. We can then pop these two elements, perform the
indicated operation on them, and push the result on the stack so that it will
be available for use as an operand of the next operator.

The following algorithm evaluates a postfix expression


Algorithm evaluation of postfix expression
{
opndstk = empty stack

Scan the input string reading one element at a time into symbol

while ( not end of input )


{
symb = next input character

if (symb is an operand)
push (opndstk, symb)
else
{

opnd2 = pop (opndstk);


opnd1 = pop(opndstk);
value = result of applying to opnd 1 and opnd 2;
push (opndstk, value);

} /* ----------------------------------------end of else */

} /*----------------------------------------end of while */

return (pop(opndstk));
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 23 of 43
EXAMPLE 1) Let us now consider a postfix expression AB+C-
Assume A=2, B=3, C=4. Suppose that we are asked to evaluate the following
postfix expression.
AB+C-
23+4-
Symb Opnd 1 Opnd 2 Value Opndstk
2 2
3 2, 3
+ 2 3 5 5
4 5, 4
- 5 4 1 1

Infix expression = A+B-C = 2 + 3 - 4 = 1


postfix expression = AB+C- = 2 3 + 4 - = 1

EXAMPLE 2) Let us now consider a postfix expression AB+CD-*


Assume A=2, B=3, C=6, D=4. Suppose that we are asked to evaluate the
following postfix expression.
AB+CD-*
23+64-*
Symb Opnd 1 Opnd 2 Value Opndstk
2 2
3 2, 3
+ 2 3 5 5
6 5, 6
4 5, 6, 4
- 6 4 2 5, 2
* 5 2 10 10

Infix expression = (A+B)*(C-D) = (2+3)*(6-4) =5*2=10


postfix expression = AB+CD-* = 2 3 + 6 4 - * = 10

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 24 of 43
EXAMPLE 3) Let us now consider an example. Suppose that we are asked to
evaluate the following postfix expression.

6 2 3 + - 3 8 2 / + * 2 $ 3 +
We show the contents of the stack opndstk and the variables symb, opnd1,
opnd2 and value after each successive iteration of the loop.

Each operand is pushed onto the operand stack as it is encountered. Since


the symbols are read as characters, we must find a method to convert the
operand characters to numbers and the operator characters to operations.
For example we must have a method for converting the character ‘5’ to
number 5 and the character ‘+’ to addition operation. The conversion of a
character to an integer can be handled easily in C. If int x is a single digit
character in C, the expression x – ‘0’ yields the numerical value of that digit.
To implement the operation corresponding to an operator symbol, we use a
functions oper that accepts the character representation of an operator and
two operands as input parameters, and return the value of the expression
obtained by applying the operator to the two operands.

POSTFIX EXPRESSION

6 2 3 + - 3 8 2 / + * 2 $ 3 +
Symb Opnd 1 Opnd 2 Value Opndstk
6 6
2 6, 2
3 6, 2, 3
+ 2 3 5 6, 5
- 6 5 1 1
3 1, 3
8 1, 3, 8
2 1, 3, 8, 2
/ 8 2 4 1, 3, 4
+ 3 4 7 1, 7
* 1 7 7 7
2 7, 2
$ 7 2 49 49
3 49, 3
+ 49 3 52 52

RESULT = 52

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 25 of 43
/*---------------------------------------------postfix.c------------------------------------------------
Program to evaluate a POSTFIX expression
*********************************************************************/
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#define MAXSTACK 80
#define TRUE 1
#define FALSE 0

struct stack
{
int top;
double item[MAXSTACK];
};
typedef struct stack stacktype;

void push(s,x)
stacktype *s;
double x;
{
s->top=s->top+1;
s->item[s->top]=x;
}

double pop(s)
stacktype *s;
{
double x;
x=s->item[s->top];
s->top=s->top-1;
return(x);
}

int isdigit( char symb)


{
if (symb>=’0’ && symb<=’9’)
return(1);
else
return(0);
}

double oper( char symb, double op1, double op2)


{
switch(symb)
{
case ‘+’ : return(op1 + op2);
case ‘-’ : return(op1 - op2);
case ‘*’ : return(op1 * op2);
case ‘/’ : return(op1 / op2);
case ‘$’ : return( pow(op1,op2));
default : printf(“%s”,”illegal operation”);
exit(1);
} /*--------------------------end of switch*/
} /*-------------------end of oper function*/
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 26 of 43
double eval (char expr[])
{
int c,position;
double opnd1,opnd2,value;
stacktype s;

s.top = -1;

for(position=0;(c=expr[position])!=‘\0’;position++)
{
if (isdigit(c))
push(&s,(double)(c-‘0’);
else
{
opnd2 = pop(&s);
opnd1 = pop(&s);
value = oper(c,opnd1,opnd2);
push(&s,value);
}
}
return(pop(&s));
}

void main()
{
char expr[50];
int position = 0;

clrscr();

printf(“enter a postfix expression \n”);

while(( expr[position++] = getchar()) != ‘\n’);

expr[--position] = ‘\0’;

printf(“The original string = %s \n”, expr);

printf( “Result= %f \n”, eval(expr));

getch();
} /*----------------------------------- end of main */

OUTPUT
enter a postfix expression
6 2 3 + - 3 8 2 / + * 2 $ 3 +
The original string = 6 2 3 + - 3 8 2 / + * 2 $ 3 +
Result = 52

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 27 of 43
CONVERTING AN EXPRESSION FROM INFIX TO POSTFIX

In our previous discussion we mentioned that expressions within innermost


parentheses must first be converted to postfix so that they can then be treated as single
operands. In this fashion parentheses can be successively eliminated until the entire
expression is converted.

Consider the two infix expressions

A+B*C and (A+B)*C

and their respective postfix versions ABC*+ and AB+C*. In each case the order of
the operands is the same as the order of the operands in the original infix expressions.

In scanning the first operation, A+B*C, the first operand, A can be inserted
immediately into the postfix expression. Clearly the first symbol cannot be inserted until after
its second operand, which has not yet been scanned, is inserted. Therefore it must be stored
away to be retrieved and inserted in its proper position. When the operand B is scanned it is
inserted immediately after A. The next symbol * has precedence over +. In the case of the
second expression the closing parenthesis indicates that the + operation should be performed
first.

Remember that in postfix, unlike infix, the operator that appears earlier in the string is
the one that is applied first.

Since precedence plays an important plays an important role in transforming infix to


postfix, let us assume the existence of a function prcd(op1,op2) where op1 and op2 are
characters representing operators. This function returns true if op1 has precedence over op2
when op1 appears to the left of op2 in an infix expression without parentheses.

Priority of operators or precedence of the operators are as follows

The function prcd() returns true i.e. 1 when the first operand has higher precedence
over the second operand otherwise it returns false i.e. 0.

prcd( ‘*’ , ‘+’ ) - true


prcd( ‘+’ , ‘+’ ) - true
prcd( ‘+’ , ‘*’ ) - false
prcd( ‘$’ , ‘$’ ) - false
prcd( ‘(’ , ‘op’) - false
prcd( op , ‘(’ ) - false
prcd( op , ‘)’ ) - true
prcd( ‘)’ , op ) - undefined

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 28 of 43
Algorithm to convert an infix string without parentheses into a postfix string.

Algorithm infixtopostfix(infix,postfix)
{
opstk = empty stack;
While (not end of input)
{
symb = next input character.

if (symb is an operand)
Add symb to postfix string;
else
{
while (!empty(opstk) && prcd(stacktop(opstk),symb))
{
topsymb = pop(opstk);
add topsymb to the postfix srting;
}
push (opstk, symb);
}
}

while (!empty(opstk))
{
topsymb = pop (opstk);
add topsymb to the postfix string;
}
}

Example 1: Converting A+B*C into postfix expression.

S.No. Symb Postfix String Opstk


1 A A
2 + A +
3 B AB +
4 * AB +*
5 C ABC +*
6 ABC *
7 ABC * +

Example 2: Converting A*B+C*D into postfix expression.

S.No. Symb Postfix String Opstk


1 A A
2 * A *
3 B AB *
4 + AB* +
5 C AB*C +
6 * AB*C +*
7 D AB*C D +*
8 AB*C D* +
9 AB*C D*+

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 29 of 43
Example 3: Converting A+B+C into postfix expression.

S.No. Symb Postfix String Opstk


1 A A
2 + A +
3 B AB +
4 + AB+ +
5 C AB+C +
6 AB+C +

Example 4: Converting A+B-C into postfix expression.

S.No. Symb Postfix String Opstk


1 A A
2 + A +
3 B AB +
4 - AB+ -
5 C AB+C -
6 AB+C -

What modifications must be made to this algorithm to accommodate parenthesis?


The answer is little when an opening parenthesis is read, it must be pushed onto the stack.
This ensures that an operator symbol appearing after a left parenthesis is pushed onto the
stack. When a closing parenthesis is read, all operators up to the first opening parenthesis
must be popped from the stack into the postfix string.

Example 3: Converting (A+B)*C into postfix expression.


S.No. Symb Postfix String Opstk
1 ( (
2 A A (
3 + A (+
4 B AB (+
5 ) AB+
6 * AB+ *
7 C AB+C *
AB+C*

Example 4: Converting (A+B)*(C-D) into postfix expression.


S.No. Symb Postfix String Opstk
1 ( (
2 A A (
3 + A (+
4 B AB (+
5 ) AB+
6 * AB+ *
7 ( AB+ *(
8 C AB+C *(
9 - AB+C *(-
10 D AB+CD *(-
11 ) AB+CD- *
12 AB+CD-*

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 30 of 43
Example 5: Converting ((A-(B+C))*D)$(E+F) into postfix expression.
S.No. Symb Postfix String Opstk
1 ( (
2 ( ((
3 A A ((
4 - A ((-
5 ( A ((-(
6 B AB ((-(
7 + AB ((-(+
8 C ABC ((-(+
9 ) ABC+ ((-
10 ) ABC+- (
11 * ABC+- (*
12 D ABC+-D (*
13 ) ABC+-D*
14 $ ABC+-D* $
15 ( ABC+-D* $(
16 E ABC+-D*E $(
17 + ABC+-D*E $(+
18 F ABC+-D*EF $(+
19 ) ABC+-D*EF+ $
20 ABC+-D*EF+$

Program to convert an infix expression to postfix expression


For simplicity, we assume all the operands are single character letters or digits. The output is
a character string. In transforming the conversion algorithm into a program, we make use of
several routines. Among those are empty, pop, push and popandtest. We also make use of a
function isoperand that returns true if ita argument ia an operand and false otherwise.

/*---------------------in2post.c--------------------------
Program to convert an Infix expr to postfix expr
----------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAXCOL 80

struct stack
{
char entry[MAXCOL];
int top;
};
typedef struct stack stacktype;

void push(s,x)
stacktype *s;
char x;
{
s->top++;
s->entry[s->top]=x;
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 31 of 43
char pop(s)
stacktype *s;
{
char x;
x=s->entry[s->top];
s->top--;
return(x);
}

int empty(stacktype s)
{
if (s.top==-1)
return(1);
else
return(0);
}

char stacktop(stacktype s)
{
return(s.entry[s.top]);
}

/* this function returns 1 if the symbol is an operand*/


int isoperand(char symb)
{
if (symb=='+'||symb=='-'|| symb=='*'|| symb=='/'
||symb=='$'||symb=='('||symb==')')
return(0);
else
return(1);
}

/*This function returns 1 if the first argument


Has precedence over the second argument */
int prcd(char opr1, char opr2)
{
int pr1,pr2;

switch(opr1)
{
case '$': pr1=3; break;
case '*': pr1=2; break;
case '/': pr1=2; break;
case '+': pr1=1; break;
case '-': pr1=1; break;
}

switch(opr2)
{
case '$': pr2=3; break;
case '*': pr2=2; break;
case '/': pr2=2; break;
case '+': pr2=1; break;
case '-': pr2=1; break;
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 32 of 43
if(pr1>=pr2)
return(1);
else
return(0);
}

/*----------- function converts infix expr to postfix expression */


void in2postfix(char ifix[], char pfix[])
{
int pos, opos=0;
char symb,topsymb;
stacktype s;

s.top = -1;
for( pos=0;(symb=ifix[pos])!='\0';pos++)
{
if(isoperand(symb))
pfix[opos++]=symb;
else
{
while(!empty(s) && prcd(stacktop(s),symb))
{
topsymb=pop(&s);
pfix[opos++]=topsymb;
}
push(&s,symb);
}
}
while(!empty(s))
{
topsymb=pop(&s);
pfix[opos++]=topsymb;
}
pfix[opos]='\0';
}

void main()
{
char infix[MAXCOL],pfix[MAXCOL];
int pos=0;
char ch;

clrscr();
printf("enter your infix string \n");
while((ch=getchar())!='\n')
{
infix[pos]=ch;
pos++;
}
infix[pos]='\0';

printf("the infix string = %s\n",infix);


in2postfix(infix,pfix);
printf("the postfix string = %s\n",pfix);
getch();
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 33 of 43
OUTPUT
enter your infix string
A+B*C
the infix string = A+B*C
the postfix string = ABC*+

OUTPUT
enter your infix string
A+B+C
the infix string = A+B+C
the postfix string = AB+C+

OUTPUT
enter your infix string
A+B-C
the infix string = A+B-C
the postfix string = AB+C-

OUTPUT
enter your infix string
A*B+C
the infix string = A*B+C
the postfix string = AB*C+

OUTPUT
enter your infix string
A*B+C*D
the infix string = A*B+C*D
the postfix string = AB*CD*+

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 34 of 43
Implementation of STACK using Linked List
The operation of adding a node to the front of a linked list is quite similar to that of
pushing an element onto a stack. A stack can be accessed only through its top element, and a
list can be accessed only from the pointer to its first element.

Similarly the operation of removing a node from front of a linked list is like popping a
stack. Thus a stack may be represented by a linear linked list. The first node of the list is the
top of the stack.

S is the external pointer referred to the stack and if S is NULL we can say that the stack is
empty.

Inserting a node to a linked list at front end:


Pushing a node on to the stack
a node in a linked list can be represented as follows
struct node
{
int data;
struct node *next;
};
typedef struct node nodetype;

nodetype *s;

assume that the linked list is a NULL list.

s = NULL;

call push() function which adds a node to the present linked list at top.

push (&s, 10);

Where s is the linked list supplied to the function push() and 10 is the data of the node to be
added to the stack at top.

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 35 of 43
/* -----------------Function to push a node to a stack */
void push(p,x)
nodetype **p;
int x;
{
nodetype *q;

q=(nodetype *)malloc(sizeof(nodetype));
q->data=x;
q->next=NULL;

if (*p==NULL)
*p=q;
else
{
q->next = *p;
*p = q;
}
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 36 of 43
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 37 of 43
Deleting a node from stack:
pop

/*------ Function to delete a node from a stack------*/


int pop(p)
nodetype **p;
{
nodetype *q;
int x;

q=*p;

if (q==NULL)
printf("Error --Empty linked list\n");
else
{
*p = q->next;
x=q->data;
free(q);
return (x);
}
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 38 of 43
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 39 of 43
Program to implement a stack using Linked List.
/*-------------------------------stkllist.c---------------------------------------------------------------
Program to create a stack using Linked list
add node at top-----------------------PUSH
delete node from top-----------------POP
traverse the stack---------------------LIST nodes
------------------------------------------------------------------------------------------------------*/
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct node
{
int data;
struct node *next;
};
typedef struct node nodetype;

void push(p,x) /* -----------------Function to push a node to a stack */


nodetype **p;
int x;
{
nodetype *q;

q=(nodetype *)malloc(sizeof(nodetype));
q->data=x;
q->next=NULL;

if (*p==NULL)
*p=q;
else
{
q->next = *p;
*p = q;
}
}

int pop(p) /*------------------ Function to delete a node from a stack */


nodetype **p;
{
nodetype *q;
int x;

q=*p;

if (q==NULL)
printf("Error --Empty linked list\n");
else
{
*p = q->next;
x=q->data;
free(q);
return (x);
}
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 40 of 43
/* -------------------------------- Function to display the contents of a stack*/
void display(p)
nodetype *p;
{
while (p!=NULL)
{
printf("%d -->",p->data);
p=p->next;
}
printf("NULL\n");
}

void main()
{
nodetype *s;
int x;
int opt;

clrscr();

s = NULL; /*---------------------------------initializing the stack*/

do
{
printf("\n Operations of STACK \n");
printf(" 1.PUSH\n 2.POP \n 3.LIST \n 4.EXIT\n");
printf("enter your option : ");
scanf("%d",&opt);

switch(opt)
{
case 1: printf("enter x");
scanf("%d",&x);
push(&s,x);
break;

case 2: x=pop(&s);
printf("the poped node is %d\n",x);
break;

case 3: printf("the contents of stack\n");


display(s);
break;
}

}while (opt<=3);

getch();
}

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 41 of 43
OUTPUT

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 1
enter x : 10

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 1
enter x : 20

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option:1
enter x : 30

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 1
enter x : 40

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 3

The elements of stack


TOP 40  30  20  10  NULL

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 2

popped element
40

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 42 of 43
Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 3

The elements of stack


TOP  30  20  10  NULL

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 2

popped element
30

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 3

The elements of stack


TOP  20  10  NULL

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 1
enter x : 70

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 3
The elements of stack
TOP  70  20  10  NULL

Operations of stack
1. PUSH
2. POP
3. LIST
4. EXIT
Enter your option: 4

----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 43 of 43

You might also like