Professional Documents
Culture Documents
Data Structures: 1.linear - Linked, Stack, Queue 2.nonlinear-Trees, Graph
Data Structures: 1.linear - Linked, Stack, Queue 2.nonlinear-Trees, Graph
Data Structures: 1.linear - Linked, Stack, Queue 2.nonlinear-Trees, Graph
Data structures are widely used in many problems. Many times these are combined or modified
according to the problem.
For example :-
1) Stack is used in implementing recursive functions
2) Queue is used in serving requests of a single shared resource (printer, disk, CPU)
3) Linked list is used in implementing stacks, queues
4) Trees and graphs are used to implement search algorithms like bfs, dfs, and hence can be
used to check connectivity of two nodes, or to find shortest distance between them
Application of stack
1.C Program to Evaluate POSTFIX Expression Using Stack
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
OUTPUT:
Enter the expression :: 245+*
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
}
main()
{
char exp[20];
char *e, x;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
}
OUTPUT:
Application of queue:
First Come First Served (FCFS) : Itis a Non-Preemptive scheduling algorithm.
FIFO (First In First Out) strategy assigns priority to process in the order in
which they request the processor. The process that requests the CPU first is
allocated the CPU first. This is easily implemented with a FIFO queue for
managing the tasks. As the process come in, they are put at the end of the
queue. As the CPU finishes each task, it removes it from the start of the
queue and heads on to the next task.
Program:
#include<stdio.h>
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);
avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);
return 0;
}
Output
Enter total number of processes(maximum 20) : 5
P[1] 1 0 1
P[2] 4 1 5
P[3] 2 5 7
P[4] 3 7 10
P[5] 5 10 15