DS Module 1
DS Module 1
• Stack:
— Definition
— Representation
— Operations and Applications:
o Polish and reverse polish expressions
o Infix to postfix conversion
o Evaluation of postfix expression
o Infix to prefix conversion
o Postfix to infix conversion
1
Data Structures with Algorithms 23MCA103
• Data Structure
Definition:
“A data structure is a storage that is used to store and organize data. It is a way of
arranging data on a computer so that it can be accessed and updated efficiently.”
• Data Structures in C are used to store data in an organised and efficient manner.
• The C Programming language has many data structures like an array, stack, queue, linked list,
tree, etc.
• A programmer selects an appropriate data structure and uses it according to their
convenience.
Data structure
int
Linear data-structure Non-Linear data-structure
char
Array Tree
float
structure
Pointer
Sets
stack Tables
Linked List
2
Data Structures with Algorithms 23MCA103
Non-Linear Data structure: Data structures where data elements are not arranged
sequentially or linearly are called non-linear data structures.
Example: Tree, Graph
Following are the important differences between Linear Data Structures and Non-linear Data Structures.
2 Levels All data elements are present at a Data elements are present
single level. at multiple levels.
3
Data Structures with Algorithms 23MCA103
5 Memory Linear data structures are not very Non-linear data structures use
utilization
memory friendly and are not utilizing memory very efficiently.
memory efficiently.
6 Examples
Graph, Map, Tree.
Array, List, Queue, Stack.
4
Data Structures with Algorithms 23MCA103
Searching-
It is used to find out the location of the data item if it exists in the given collection of
data items.
Inserting-
It is used to add a new data item in the given collection of data items.
Deleting-
It is used to delete an existing data item from the given collection of data items.
Sorting-
It is used to arrange the data items in some order i.e., in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
Merging-
It is used to combine the data items of two sorted files into single file in the sorted form.
5
Data Structures with Algorithms 23MCA103
2. Stack
• Definition:
“A stack is a Linear collection of items in which all additions and deletions are restricted to one
end, called the top”.
A stack is a linear data structure in which all the insertion and deletion of data or you can say its
values are done at one end only, rather than in the middle. Stacks can be implemented by using
arrays.
• Properties of stack:
6
Data Structures with Algorithms 23MCA103
Push()
Inserting an element into the stack is known as push operation.
Only one item is inserted at a time and item has to be inserted only from the top of the stack.
When the elements are being inserted there is possibility of stack being full.
Once the stack is full, it is not possible to insert any element.
Trying to insert an element, even when the stack is full result in stack overflow.
Hence while inserting element into the stack we must check for overflow condition.
Example: Stack contents after inserting 4 items 30,20,25 and 10 one after the other with a MAX 4.
MAX is a stack size.
if(top ==MAX-1)
{
printf(”\n STACK OVERFLOW ..”);
}
stack [++top] = item;
printf( ”\n . . Element pushed Successfully. . ” ) ;
}
7
Data Structures with Algorithms 23MCA103
Pop()
Deleting an element from top of the stack.
Only one item is deleted at a time and item has to be deleted only from the top of the stack.
When the elements are being deleted there is a possibility of stack being empty.
Once the stack is empty, it is not possible to delete any element.
Trying to delete any element, even when the stack is empty results in Stack Underflow.
Hence while deleting element from the stack we must check for underflow condition.
Example: Performing pop operation when stack already contains 30, 20, 25 and 10
if(top == -1)
{
printf(“\n .. STACK UNDERFLOW …”);
return 0;
}
8
Data Structures with Algorithms 23MCA103
//function declaration
#define Max 3
int top=-1; //global variable
void main( )
while(1)
{
printf(”\n\n Stack Operations :\n™);
printf(”\n 1. Push. ”);
printf(”\n 2. Pop.”);
printf(”\n 3. Display. ”);
printf(”\n 4. (or any other) Exit... ”);
6
Data Structures with Algorithms 23MCA103
case 2 :
item = pop(stack); //function call
if( item)
//popped item value will be displayed
printf( "\ n Popped item is : %d “, item) ;
break;
case 3 :
display(stack); //function call
break;
default: exit(0);
}
if(top ==MAX-1)
{
printf(”\n STACK OVERFLOW ..”);
}
stack [++top] = item;
printf( ”\n . . Element pushed Successfully. . ” ) ;
}
7
Data Structures with Algorithms 23MCA103
//function definition
int pop(int *stack)
{
int item;
if(top == -1)
{
printf(“\n .. STACK UNDERFLOW …”);
return 0;
}
if(top == -1)
{
printf(“\n .. Stack is Empty ..”);
return;
}
return;
8
Data Structures with Algorithms 23MCA103
• Arithmetic Expression:
— An expression is defined as a number of operands combined using several operators.
1. Infix Notation
• Form: “operator is placed in-between the two operands”
• Example: A + B, 5 — 6
2. Polish Notation
3. (Prefix expression)
• Prefix notation was introduced by the “Polish logician Lukasiewicz”, and is
sometimes called “Polish notation”.
• Form: “operator is placed in beginning of the two operands”
• Example: +AB, - 5 6
9
Data Structures with Algorithms 23MCA103
Infix expression:
• You need to check operator precedence and Associativity.
• Brackets () will be included.
• For Example: (a+b+c*d)
• Multiplication and Division are done before addition and subtraction.
• Associativity for arithmetic operator is from left to right.
No Operator Meaning
1 $ or ^ Exponentiation
2 *, / Multiplication and division
3 +, - Addition and subtraction
Infix Expression:
Example: 2+3*4 = 2+12= 14.
1. 5+3*4/2*12
2. 3*(4%2)/2
3. 3*4+5*6
4. 3*(4+5)*6
10
Data Structures with Algorithms 23MCA103
2. At each step convert the parenthesized infix expression to prefix or postfix as needed.
(A+(*BC)) +D ((A+(BC*))+D
( (+A*BC) + D ((ABC*+)+D)
++A*BCD ABC*+D+
A * B + C *D
A+B/C$D- E* (F+ G)
11
Data Structures with Algorithms 23MCA103
6. If scanned symbol is right bracket ’)’, pop the stack and print all output string character until
‘(‘ is encountered and discard both the brackets.
7. After reading all the symbols, if stack is not empty pop and add it to the postfix expression.
• Algorithm
1. Set operator stack to empty.
2. Symbol = (Scan/Read the infix expression from left to right one character at a time).
a) If ( Symbol = operand )
— Add symbol to postfix
b) If ( Symbol = ‘(’ )
— Push symbol to stack
12
Data Structures with Algorithms 23MCA103
c) If ( Symbol = ‘)’)
— while ( StackTop !=’(’)
Pop stack and add to postfix
— Remove open brace from stack and discard
d) Otherwise If ( Symbol = operator)
— while (precedence(Symbol) <= precedence(StackTop) )
Pop top operator and add it to postfix string
— Push symbol to stack. // as precedence of Symbol is High
Priority Table:
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case ' * ' :
case '/': return 3;
case ' $' :
case ‘^’ : return 4;
13
Data Structures with Algorithms 23MCA103
Infix Expressions
1. ((A*(B+D)/E) – (F *(G+H)/K))
2. A+(B*C)/D
3. ( A + B ) * ( C — D ) ^ E * F
13
Data Structures with Algorithms 23MCA103
#include<stdio.h>
#include<ctype.h›
char pop()
{
return (stack[top--]);
}
15
Data Structures with Algorithms 23MCA103
• Algorithm
1. Set Operand Stack to empty
2. Symbol = (Read/Scan the postfix input from left to right one character at a time).
a. If (symbol = operand)
— Push symbol to stack.
b. If (symbol = operator)
— Pop first operand2 and then operand1
— Find result by Applying the operator on operand1 operator operand2.
— Push the result back to stack.
3. Repeat step-2 till end of in put string.
4. Pop the final result and Return
Example:
456*+
62 3* + 5 –
54*65*-
Expression: 456*+
16
Data Structures with Algorithms 23MCA103
17
Data Structures with Algorithms 23MCA103
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAXSIZE 30
int s[MAXSIZE];
int top=-1;
int isdig(char);
int main()
{
char symbol,postfix[30];
int a,b,res,i;
void push(int);
int pop();
int op(int, int, char);
printf(" Enter a Postfix expression\n");
scanf("%s",postfix);
for(i=0;i<strlen(postfix);i++)
{
symbol=postfix[i];
if(isdig(symbol))
push(symbol-'0');
else
{
a = pop();
b = pop();
res = op(b,a,symbol);
push(res);
}
}
printf("The result of the expression is = ");
printf("%d\n",pop());
18
Data Structures with Algorithms 23MCA103
return 0;
}
int pop()
{
if(top!=-1)
return s[top--];
else
{
printf("Stack underflow\n");
return 0;
}
}
void push(int item)
{
if(top!= MAXSIZE-1)
s[++top]=item;
else
printf("\nStak Overflow\n");
}
int op(int op1,int op2,char symbol)
{
switch(symbol)
{
case '+': return op1 + op2;
case '-': return op1 - op2;
case '*': return op1 * op2;
case '/': return op1 / op2;
}
}
int isdig(char symbol1)
{
return (symbol1>='0' && symbol1<='9');
}
19
Data Structures with Algorithms 23MCA103
3. Infix-to-Prefix Conversion
• Steps to convert infix to prefix expression
1. First, reverse the infix expression given in the problem.
2. Scan the expression from left to right.
3. Whenever the operands arrive, print them.
4. If the operator arrives and the stack is found to be empty, then simply push the operator
into the stack.
5. If the incoming operator has higher precedence than the TOP of the stack, push the
incoming operator into the stack.
6. If the incoming operator has the same precedence with a TOP of the stack, push the
incoming operator into the stack.
7. If the incoming operator has lower precedence than the TOP of the stack, pop, and print
the top of the stack. Test the incoming operator against the top of the stack again and
pop the operator from the stack till it finds the operator of a lower precedence or same
precedence.
8. If the incoming operator has the same precedence with the top of the stack and the
incoming operator is ^, then pop the top of the stack till the condition is true. If the
condition is not true, push the ^ operator.
9. When we reach the end of the expression, pop, and print all the operators from the top
of the stack.
10. If the operator is ')', then push it into the stack.
11. If the operator is '(', then pop all the operators from the stack till it finds ‘)’ closing
bracket in the stack.
12. If the top of the stack is ')', push the operator on the stack.
13. At the end, reverse the output.
20
Data Structures with Algorithms 23MCA103
• Algorithm
6. Pop all elements from stack till stack becomes empty and add to the output string.
21
Data Structures with Algorithms 23MCA103
S S
1
^ Push to stack ^ S
2
3 E SE
+ Compare(^,+), pop ^, push + SE^
4
incoming operator into stack
5 D SE^D
* Compare(+,*) + is not highest + * SE^D
6
Precedence than *, so push to
stack.
7 ( Push + *( SE^D
8 C + *( SE^DC
9 ^ +*(^ SE^DC
Push
10 B +*(^ SE^DCB
11 + Compare(^,+), pop ^, push +*(+ SE^DCB^
incoming operator into stack
12 A +*(+ SE^DCB^A
13 ) Pop + +* SE^DCB^A+
14 Pop remaining element from SE^DCB^A+*+
the stack
Example 2: A + B * C - ( D - E )
22
Data Structures with Algorithms 23MCA103
Data Structures with Algorithms
1. Read the symbol from the input .based on the input symbol go to step 2 or 3.
5. Create a new string and put the operator between this operand in string.
7. At the end only one value remain in stack which is our infix expression.
• Algorithm
1. Scan operand stack to empty
2. Symbol = (scan Postfix String from Left to Right till null).
a. If(Symbol = Operand) then
i. Push it on to the Stack.
b. If(Symbol = Operator) then
i. Pop Operand 1 and Operand 2
ii. Concatenate them with operator using Infix notation.
iii. Use parentheses properly to ensure correct order of operators.
iv. Push the resultant expression on to the Stack.
3. Repeat the above steps till the Postfix string is not scan ned completely.
4. Pop the stack and return as infix expression.
23
Data Structures with Algorithms 23MCA103
24
Data Structures with Algorithms 23MCA103
16 Write an algorithm to convert an infix expression to postfix. Trace the algorithm for 10
following infix expression ( ( A — ( B + C ) ) * D ) $ ( E + F )
17 Write an algorithm to evaluate a Postfix expression. Trace the algorithm for 10
following postfix expression showing contents of stack: 6 2 3 + - 3 8 2 / + * 2 $ 3 +
25