Application of Stack
Application of Stack
Classification
LINEAR DATA STRUCTURE
Arrays
Arrays are the set of homogeneous data elements stored in RAM. So, they can hold
only one type of data. The data may be all integers, all floating numbers or all
characters. Values in an array are identified using array name with subscripts.
Single sub-scripted variables are known as
a one-dimensional array or linear array; two sub-scripted variables are referred as a
two dimensional array.
One Dimensional Array
Two Dimensional Array
List
A list is a collection of a variable number of data items. Lists fall in the non-
primitive type of data structure in the classification of data structure. Every
element on a list contains at least two fields, one is used to store data and the other
one is used for storing the address of next element.
Files
Files contain data or information, stored permanently in the secondary storage
device such as Hard Disk and Floppy Disk. It is useful when we have to store and
process a large amount of data. A file stored in a storage device is always
identified using a file name like HELLO.DAT or TEXTNAME.TXT and so on.
A file name normally contains a primary and a secondary name which is separated
by a dot (.).
Stack
Like arrays, a stack is also defined as an ordered collection of elements. A stack is
a nonprimitive linear data structure having a special feature that we can delete and
insert elements from only one end, referred as TOP of the stack. The stack is also
known as Last In First Out (LIFO) type of data structure for this behavior.
When we perform insertion or deletion operation on a stack, its base remains
unchanged but the top of the stack changes. Insertion in a stack is called Push and
deletion of elements from the stack is known as Pop.
We can implement a stack using 2 ways
Static implementation (using arrays)
Dynamic implementation (using pointers)
Queues
Queues are also non-primitive linear data structure. But unlike stacks, queues are
the
First In First Out (FIFO) type of data structures. We can insert an element in a
queue from the REAR end but we have to remove an element from the only
FRONT end.
We can also implement queues using 2 ways
Using arrays
Using pointers
NON LINEAR DATA STRUCTURE
Trees
Trees fall into the category of non-primitive non-linear data structures in the
classification of data structure. They contain a finite set of data items referred as
nodes. We can represent a hierarchical relationship between the data elements
using trees.
A Tree has the following characteristics
The top item in a hierarchy of a tree is referred as the root of the tree.
The remaining data elements are partitioned into a number of mutually exclusive
subsets and they itself a tree and are known as the sub tree.
Unlike natural trees, trees in the data structure always grow in length towards
the bottom.
Graph
Graph falls in the non-primitive non-linear type of data structure in the
classification of data structure. Graphs are capable of representing different types
of physical structures. Apart from computer science, they are used broadly in the
fields of Geography, Chemistry & Engineering Sciences. A graph normally a
combination of the set of vertices V and set of edges E.
STACK DATA STRUCTURE INTRODUCTION
Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First
In Last Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
Peek or Top: Returns top element of stack.
Is Empty: Returns true if stack is empty, else false.
1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking
4. Memory Management
Expression Representation
#include <stdio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
push(char elem)
{
s[++top]=elem;
return 0;
}
char pop()
{
return(s[top--]);
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
return 0;
}
void main()
{
char infx[50], pofx[50], ch, elem;
int i=0, k=0;
printf("\n\nEnter Infix Expression: ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop();
}
else
{
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\n Given Infix Expression: %s \n Postfix Expresssion:
%s\n",infx,pofx);
}
Output:
2. Infix to Prefix
Algorithm for Infix to Prefix Conversion:
Step 1: Insert “)” onto stack, and add “(” to end of the A .
Step 2: Scan A from right to left and repeat Step 3 to 6 for each element of A until
the stack is empty .
Step 7: Exit
#include<stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX 50
struct infix
{
char target[MAX] ;
char stack[MAX] ;
char *s, *t ;
int top, l ;
};
void initinfix ( struct infix * ) ;
void setexpr ( struct infix *, char * ) ;
void push ( struct infix *, char ) ;
char pop ( struct infix * ) ;
void convert ( struct infix * ) ;
int priority ( char c ) ;
void show ( struct infix ) ;
void main( )
{
struct infix q ;
char expr[MAX] ;
clrscr( ) ;
initinfix ( &q ) ;
printf ( "\nEnter an expression in infix form: " ) ;
gets ( expr ) ;
setexpr ( &q, expr ) ;
convert ( &q ) ;
printf ( "The Prefix expression is: " ) ;
show ( q ) ;
getch( ) ;
}
/* initializes elements of structure variable */
void initinfix ( struct infix *pq )
{
pq -> top = -1 ;
strcpy ( pq -> target, "" ) ;
strcpy ( pq -> stack, "" ) ;
pq -> l = 0 ;
}
/* reverses the given expression */
void setexpr ( struct infix *pq, char *str )
{
pq -> s = str ;
strrev ( pq -> s ) ;
pq -> l = strlen ( pq -> s ) ;
*( pq -> target + pq -> l ) = '\0' ;
pq -> t = pq -> target + ( pq -> l - 1 ) ;
}
/* adds operator to the stack */
void push ( struct infix *pq, char c )
{
if ( pq -> top == MAX - 1 )
printf ( "\nStack is full.\n" ) ;
else
{
pq -> top++ ;
pq -> stack[pq -> top] = c ;
}
}
/* pops an operator from the stack */
char pop ( struct infix *pq )
{
if ( pq -> top == -1 )
{
printf ( "Stack is empty\n" ) ;
return -1 ;
}
else
{
char item = pq -> stack[pq -> top] ;
pq -> top-- ;
return item ;
}
}
/* converts the infix expr. to prefix form */
void convert ( struct infix *pq )
{
char opr ;
while ( *( pq -> s ) )
{
if ( *( pq -> s ) == ' ' || *( pq -> s ) == '\t' )
{
pq -> s++ ;
continue ;
}
if ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) )
{
while ( isdigit ( *( pq -> s ) ) || isalpha ( *( pq -> s ) ) )
{
*( pq -> t ) = *( pq -> s ) ;
pq -> s++ ;
pq -> t-- ;
}
}
if ( *( pq -> s ) == ')' )
{
push ( pq, *( pq -> s ) ) ;
pq -> s++ ;
}
if ( *( pq -> s ) == '*' || *( pq -> s ) == '+' || *( pq -> s ) == '/' ||*( pq -> s ) ==
'%' || *( pq -> s ) == '-' || *( pq -> s ) == '$' )
{
if ( pq -> top != -1 )
{
opr = pop ( pq ) ;
while ( priority ( opr ) > priority ( *( pq -> s ) ) )
{
*( pq -> t ) = opr ;
pq -> t-- ;
opr = pop ( pq ) ;
}
push ( pq, opr ) ;
push ( pq, *( pq -> s ) ) ;
}
else
push ( pq, *( pq -> s ) ) ;
pq -> s++ ;
}
if ( *( pq -> s ) == '(' )
{
opr = pop ( pq ) ;
while ( opr != ')' )
{
*( pq -> t ) = opr ;
pq -> t-- ;
opr = pop ( pq ) ;
}
pq -> s++ ;
}
}
while ( pq -> top != -1 )
{
opr = pop ( pq ) ;
*( pq -> t ) = opr ;
pq -> t-- ;
}
pq -> t++ ;
}
/* returns the priotity of the operator */
int priority ( char c )
{
if ( c == '$' )
return 3 ;
if ( c == '*' || c == '/' || c == '%' )
return 2 ;
else
{
if ( c == '+' || c == '-' )
return 1 ;
else
return 0 ;
}
}
/* displays the prefix form of given expr. */
void show ( struct infix pq )
{
while ( *( pq.t ) )
{
printf ( " %c", *( pq.t ) ) ;
pq.t++ ;
}
}
Output:
Postfix to Infix
Following is an algorithm for Postfix to Infix conversion:
Step 6: Else,
a. Delete the top 2 values from the stack.
b. Put the operator, with the values as arguments and form a string.
c. Encapsulate the resulted string with parenthesis.
d. Insert the resulted string back to stack.
Step 7: If there is only one value in the stack, that value in the stack is the desired
infix string.
Step 8: If there are more values in the stack, show error /* The user input has too
many values */
efg-+he-sh-o+/* NULL
fg-+he-sh-o+/* “e”
g-+he-sh-o+/* “f”
“e”
-+he-sh-o+/* “g”
“f”
“e”
+he-sh-o+/* “f”-“g”
“e”
he-sh-o+/* “e+f-g”
e-sh-o+/* “h”
“e+f-g”
-sh-o+/* “e”
“h”
“e+f-g”
sh-o+/* “h-e”
“e+f-g”
h-o+/* “s”
“h-e”
“e+f-g”
-o+/* “h”
“s”
“h-e”
“e+f-g”
o+/* “h-s”
“h-e”
“e+f-g”
+/* “o”
“s-h”
“h-e”
“e+f-g”
/* “s-h+o”
“h-e”
“e+f-g”
* “(h-e)/( s-h+o)”
“e+f-g”
NULL “(e+f-g)* (h-e)/( s-h+o)”
#include <stdio.h>
#include <stdlib.h>
int top = 10;
struct node
{
char ch;
struct node *next;
struct node *prev;
} *stack[11];
typedef struct node node;
void push(node *str)
{
if (top <= 0)
printf("Stack is Full ");
else
{
stack[top] = str;
top--;
}
}
node *pop()
{
node *exp;
if (top >= 10)
printf("Stack is Empty ");
else
exp = stack[++top];
return exp;
}
void convert(char exp[])
{
node *op1, *op2;
node *temp;
int i;
for (i=0;exp[i]!='\0';i++)
if (exp[i] >= 'a'&& exp[i] <= 'z'|| exp[i] >= 'A' && exp[i] <= 'Z')
{
temp = (node*)malloc(sizeof(node));
temp->ch = exp[i];
temp->next = NULL;
temp->prev = NULL;
push(temp);
}
else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/' || exp[i] == '^')
{
op1 = pop();
op2 = pop();
temp = (node*)malloc(sizeof(node));
temp->ch = exp[i];
temp->next = op1;
temp->prev = op2;
push(temp);
}
}
void display(node *temp)
{
if (temp != NULL)
{
display(temp->prev);
printf("%c", temp->ch);
display(temp->next);
}
}
void main()
{
char exp[50];
clrscr();
printf("Enter the postfix expression :");
scanf("%s", exp);
convert(exp);
printf("\nThe Equivalant Infix expression is:");
display(pop());
printf("\n\n");
getch();
}
Output:
4. Prefix to Infix
Expression Stack
-bc+-pqr Empty
/-bc+-pq “q”
“r”
/-bc+- “p”
“q”
“r”
/-bc+ “p-q”
“r”
/-bc “p-q+r”
/-b “c”
“p-q+r”
/- “b”
“c”
“p-q+r”
/ “b-c”
“p-q+r”
NULL “((b-c)/((p-q)+r))”
Algorithm for Prefix to Infix Conversion
Step 1: The reversed input string is inserted into a stack -> prefixToInfix(stack)
#include <string.h>
#include <ctype.h>
Output: