Professional Documents
Culture Documents
DATA STRUCTURES
STACKS
***************************************************************************
Stacks: Introduction to Stacks,
Array Representation of Stacks, Operations on Stacks,
Linked list Representation of Stacks, Operations on Linked 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.
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;
s.top = s.top + 1;
s.entry[s.top] = x;
s->top = s->top + 1;
s->entry[s->top] = x;
push(&s,x);
----------------------------------------------------------------------------------------------------------------
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;
x = s.entry[s.top];
s.top = s.top – 1;
x = s->entry[s->top];
s->top = s->top – 1;
x = pop(&s);
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.
----------------------------------------------------------------------------------------------------------------
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”);
}
int empty(s)
stacktype s;
{
if (s.top == -1)
return(1);
else
return(0);
}
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;
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;
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.
----------------------------------------------------------------------------------------------------------------
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]);
for(i=0;i<n;i++)
a[i]=pop(&s);
***********************************************************
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);
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.
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.
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
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.
Scan the input string reading one element at a time into symbol
if (symb is an operand)
push (opndstk, symb)
else
{
} /* ----------------------------------------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
----------------------------------------------------------------------------------------------------------------
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.
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);
}
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();
expr[--position] = ‘\0’;
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
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.
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.
----------------------------------------------------------------------------------------------------------------
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;
}
}
----------------------------------------------------------------------------------------------------------------
Dr.DSK I B.TECH II Semester CSE : Data Structures STACKS Page 29 of 43
Example 3: Converting A+B+C into postfix expression.
----------------------------------------------------------------------------------------------------------------
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+$
/*---------------------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]);
}
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);
}
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';
----------------------------------------------------------------------------------------------------------------
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.
nodetype *s;
s = NULL;
call push() function which adds a node to the present linked list at top.
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
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;
q=(nodetype *)malloc(sizeof(nodetype));
q->data=x;
q->next=NULL;
if (*p==NULL)
*p=q;
else
{
q->next = *p;
*p = q;
}
}
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();
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;
}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
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
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
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