DS - Module-1-I
DS - Module-1-I
Algorithms
• Stack: Definition
Representation
- Stack as ADT
• Data-type Definition:
A data type is a collection of data together with a set of operations for creating
and manipulating them.
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 Graph
Pointer
union Sets
stack Tables
Queue
Linked List
Linear Data structure: A Linear data structure have data elements arranged in sequential
manner and each member element is connected to its previous and next element. Such
data structures are easy to implement as computer memory is also sequential.
Example: Array, Stack, Queue, Linked List etc.
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.
Non-linear data
Linear data structures can be traversed structures are not easy to
4 Traversal
completely in a single run. traverse
and needs multiple runs
to
be traversed completely.
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".
push{)
�-�-
-
I
- I
z-f-top
pop () I I
I I
I I
I I
I I
I I
I I
L J
• Properties of stack:
o Push
- Insert new elements onto the top of Stack.
o Pop
- Remove an element from the top of stack.
o isEmpty
- True if stack is empty.
o Display
- Display the contents of the stack.
Q2. Write a program to implement stack operation using array as a data structure
(without using Structure).
Implement following conditions on stack.
1. Stack overflow
2. Stack underflow
3. Stack empty
4. Stack full
/* Stack implementation */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
/* Program 1: Stack of tntegers to perform the fottowing */
#define MAX 3
int top = -1;
void main()
{
int stack[MAX];
int choice, item;
while(l)
{
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 ... ");
switch(choice)
{
case 1:
printf("\n Enter the element to be pushed: ");
scanf( "%d", &item);
push(stack, item);
break;
case 2:
item= pop(stack);
if( item)
printf("\n Popped item is: %d .",item);
break;
case 3:
display( stack);
break;
default: exit(0);
}
}
}
II end of main function
if(top == MAX-1)
printf("\n .. Now Stack Is Full .. ");
}
Q3. Write a program to implement stack operation using a structure. Implement following
conditions on stack. Push(), Pop(), Display(), Overflow() & Underflow().
• Arithmetic Expression:
- An expression is defined as a number of operands combined using several operators.
1. Infix Notation
1. Infix Notation
o Form: "operator is placed in-between the two operands"
o Example: A+ B, 5 - 6
o Example: +AB, - 5 6
operands"
• Infix Notation:
o Operator precedence
o Associativity.
No Operator Meaning
1 $ or' Exponentiation
2. At each step convert the parenthesized infix expression to prefix or postfix as needed.
7 ( (+A*BC) + D ) 7 ( (ABC*+) + D )
7 + + A * B c D 7 A B C * + D +
A*B+C*D 7 7
A+B/C$D-E*(F+ G) 7 7
• Algorithm
1. Set operator stack to empty.
2. Symbol= ( Read the infix expression from left to right one character at a time).
a) If ( Symbol = operand )
Add symbol to postfix
5. Pop all elements from stack till stack becomes empty and add to the Postfix Expression.
Priority Table:
case '#':
return 0· case 1 ( 1 :
'
return 1 · case '+':
'
case • - 1 :
return 2.
* '
case 1 1 0
'
Q4. Write a function that convert the infix expression to postfix expression that also includes
braces (Parenthesis)
r: infixToPostfixO f1111ctio11 */
void infixToPostfix(char *infix, char* postfix)
{
char symbol, brace;
inti= 0, k = 0;
push('#');
postfix[k] = '\0';
}
Output:
char pop()
{
return (stack[top--]);
}
int priority(char op)
{ /* F1111ctio11 for precedence */
switch (op)
{
case '#': return 0;
case 1 ( 1 : return 1;
case '+':
case • - 1 : return 2;
case 1 * 1 0
• Algorithm
2. Symbol= (Read the postfix input from left to right one character at a
time). a. If (symbol = operand}
- Push symbol to
Steps
Evaluate Postfix Expression: 5 4 * 6 5
Symbol Action Opl Op2 result
. -
Operand stack
1 5 Push 5
2 4 Push 5,4
3 * Pop op2 5 4 20 20
pop opl
4 6 Push 20,6
5 5 Push 20,6,5
6 * Pop op2 6 5 30 20,30
pop opl
7 - Pop op2 20 30 -10 -10
pop opl
8 Null Retum -10
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#define MAX 20
float stack[MAX];
int top;
int main()
{
char postfix[MAX];
float result;
printf("\n Enter a valid postfix expression: ");
scanf( "%s", postfix);
result = evalPost(postfix);
Output:
• Algorithm
c) if (Symbol= operand)
Add to Output string
d) if (Symbol= operator)
if precedence(symbol) > precedence(stackTop)
./ push symbol to stack
6. Pop all elements from stack till stack becomes empty and add to the output string.
2 ) Push #' )
3 E Operand Add to output #, ) E
4 > Push #, ), - E
• Algorithm
3. Repeat the above steps till the Postfix string is not scanned completely.
2 B Push A, B
Infix string= ( ( A * B ) - ( C * D ) )
Additional topics
• Array as ADT
ADT Array
Abstract typedef<< eltype, ub >>
ARRTYPE Condition type(ub) == int;
Abstract eltype extract (a, ; ) /" reading elt = a[i] */
ARRTYPE a;
inti;
Precondition:
O <= i < ub;
Postcondition:
extract== a[i];
Abstract store ( a, ;, val) /" written a[i] = elt */
ARRTYPE a;
inti;
eltype val;
Precondition:
O <= i < ub;
Postcondition:
a[i] == val;
End Array
• Operations on Array :
- Create - A operation that creates an Array
Insert- A operation that inserts a given element into a given location in an array
- Search - A operation that returns the first occurrence of element in a array, else return -1.
• Stack as ADT
ADT Stack
abstract typedef <<eltype>> STACK (eltype)
abstract empty(s)
STACK (eltype) s·'
Postcondition empty ( len(S) -- 0);
abstract eltype pop(S)
STACK (eltype)
s·'
Precondition :
empty(S) == FALSE;
Postcondition: pop -- first(S');
s sub(S' , 1, len(S') - 1);
abstract eltype push( S, elt )
STACK (eltype) S;
eltype elt;
Postcondition S -- < elt> + S';
End ADT
For example: ( (a+ b) * c) is a valid expression, because the left parentheses at position 1st
has a matching right parentheses at 9th position and similarly, left parentheses at 2nd position
has a matching right parentheses at position 6th.
The expression ( (a+ b) and (a+ b)) are invalid, since there is a ')' missing for a '(' at position
1 and '(' missing for a ')' at position 6 respectively.
So, to check whether an Infix expression has matching parentheses or not. Stack is
useful because, if we scan the input expression from left to right, each right parentheses is
matched to the most recently seen unmatched left parenthesis. We can simply save the left
parentheses in stack until we encounter a matching right parentheses. The following C code that
does this job
Q6. Write C program to check Parentheses matching or not in the Infix Expression.
• Algorithm
1. Set operand Stack to empty.
2. Read next character from input String.
a. Add character to stack.
3. Repeat step 2 till end of string.
4. Pop character from stack
a. Add popped character to string rev.
5. Repeat step 4 till stack is empty.
6. Add null character to string rev.
7. Display rev.
#include <stdio.h>
#define MAX 20
char stack[MAX];
int top;
void push(char item)
{
stack[++top]=item;
}
char pop()
{
return(stack[top--]);
}
int main()
{
char input[MAX], rev[MAX];
inti;
top= -1;
rev[i] = '\0';
getch();
}
1
Define Data structures. Explain different types of data structures. 8
5 Define stack with diagram? Write a C program to reverse a string using stack. 8
n (A+B)'(C-D)'E'F
g) A+( ( ( B-C)' ( D-E )+F )/G )+H
8 Convert any two of the following into its prefix and postfix form. 6
i) (A+B)'C-D$E'F
ii) A-B/C'D$E
iii) (A+B)$(c+D-E)' F
10 Write an algorithm to evaluate a postfix expression. Trace the algorithm with 6+2
stack contents for the following expression.
a) ABC+*CBA-+* with A=l, 8=2, C=3.
13 Explain with algorithm how stack is applied for evaluating a postfix arithmetic 8
expression.
16 Define Prefix and Postfix expressions. Write a program to convert infix to postfix
8
expressions.
7 ( A + (*BC) ) + D 7 ( (A + (BC*)) + D
7 ( (+A*BC) + D ) 7 ( (ABC*+) + D )
7 + + A * B c D 7 A B C * + D +
A*B+C*D
A+B/C$D-E*(F+ G) • '
.-
t
,
(A+B)*(C-D)$E*F
A+((B$C)*D)-(E+F)/(G*H))+I
(A+B'C)/D+E
A*B/C+(B+C)*D
No Operator Meaning
1 $ or' Exponentiation
Convert the following infix expression from infix to prefix and postfix.
A+B-C
A-B/(C'D$E)
� -
'
, •\
- What are the major data structures used in the following areas: RDBMS, Network data
model & Hierarchical data model?
Ans
The major data structures used are as follows:
o RDBMS -Array (i.e., Array of structures)
o Network data model -Graph
o Hierarchical data model -Trees