Ds Module1
Ds Module1
Module 1- Introduction
INTRODUCTION TO DATA
STRUCTURES: Data Structures,
Classifications (Primitive& Non-Primitive),
Module 1 Syllabus Data structure Operations
Review of pointers and dynamic Memory
Allocation,
ARRAYS and STRUCTURES: Arrays,
Dynamic Allocated Arrays, Structures and
Unions,Polynomials, Sparse Matrices,
representation of Multidimensional Arrays,
Strings
STACKS: Stacks, Stacks Using Dynamic
Arrays, Evaluation and conversion of
Expressions
Primitive Data Structures: Primitive data structures are the basic data structures that
directly operate upon the machine instructions.They are the fundamental data types which
are supported by a programming language. Some basic data types are integer, real,
character, and Boolean. The terms ‘data type’, ‘basic data type’, and ‘primitive data type’
are often used interchangeably.
Non-Primitive Data Structures: Non-primitive data structures are those data structures
which are created using primitive data structures. Examples of such data structures
include linked lists, stacks, trees, and graphs.
Based on the structure and arrangement of data, non-primitive data structures is further
classified into
Linear Data Structure
Non-linear Data Structure
Linear data Structures :If the elements of a data structure are stored in a linear or
sequential order, then it is a linear data structure.Linear data structures can be represented
in memory in two different ways.
One way is to have to a linear relationship between elements by means of
sequential memory locations.
The other way is to have a linear relationship between elements by means of links.
Examples include arrays, linked lists, stacks, and queues.
1. Array: Simplest type of data structure is linear array. It is the list of finite
numbers n of similar data elements referenced respectively by a set of n
consecutive numbers. Ex: array of students consisting of six students shown in
fig.
2. A linked list is a very flexible, dynamic data structure in which elements (called
nodes) form a sequential list. A linked list, every node contains the following two
types of data:
The value of the node or any other data that corresponds to that node
A pointer or link to the next node in the list
2
DATA STRUCTURES AND APPLICATIONS (BCS304)
The last node in the list contains a NULL pointer to indicate that it is the end or tail of
the list. Since the memory for a node is dynamically allocated when it is added to the
list, the total number of nodes that may be added to a list is limited only by the
amount of memory available. Figure shows a linked list of four nodes shown in fig.
3. A stack is a linear data structure in which insertion and deletion of elements are
done at only one end, which is known as the top of the stack. Stack is called a
last-in, first-out (LIFO) structure because the last element which is added to the
stack is the first element which is deleted from the stack.
4. A queue is a first-in, first-out (FIFO) data structure in which the element that is
inserted first is the first one to be taken out. The elements in a queue are added at
one end called the rear and removed from the other end called the front.
Non-linear data Structures If the elements of a data structure are not stored in a
sequential order, then it is a non-linear data structure.
3
DATA STRUCTURES AND APPLICATIONS (BCS304)
4
DATA STRUCTURES AND APPLICATIONS (BCS304)
4. Inserting- It is used to add a new data item in the given collection of data items.
5. Deleting- It is used to delete an existing data item from the given collection of data
items.
6. 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.
7. Merging- It is used to combine the data items of two sorted files into single file in the
sorted form.
scanf("%d", &num);
printf("\n The number that was entered is : %d", *pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10
Note : The value of *&num is equivalent to simply writing num.
1.4.2Pointer expressions and Pointer arithmetic
Pointer variables can be used in expressions. In C Programmer may:
Add or subtract integers from pointers.
Subtract two pointers of the same type.
Use shorthand operators with pointer variables.
Compare pointers using relational operators.
Postfix unary increment (++) and decrement (--) operators have greater
precedence than the dereference operator (*).
Write (*ptr)++ , to increment the value of the variable whose address is stored in
ptr.
1.4.3Null Pointers
A null pointer is a special pointer value that does not point to any valid memory
address.
To declare a null pointer, use the predefined constant NULL,int *ptr = NULL;
Check whether a pointer variable is null by writing if(ptr == NULL).
Initialize a pointer to null using the constant 0, but it is better to use NULL to
avoid ambiguity.int *ptr; ptr = 0;
A function that returns pointer values can return a null pointer when it is unable to
perform its task.
A generic pointer is a pointer variable that has void as its data type.
The void pointer, or the generic pointer, is a special type of pointer that can point
to variables of any data type.
It is declared like a normal pointer variable but using the void keyword as the
pointer’s data type.
For example:
#include <stdio.h>
int main()
{
6
DATA STRUCTURES AND APPLICATIONS (BCS304)
int x=10;
char ch = ‘A’;
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
gp = &ch;
printf("\n Generic pointer now points to the character= %c", *(char*)gp);
return 0;
}
Output
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A
If pointers are used incorrectly, they can lead to bugs that are difficult to unearth.
For example, if a pointer is used to read a memory location but that pointer is pointing
to an incorrect location, then we may end up readinga wrong value.
An erroneous input always leads to an erroneous output.
Example:
int x, *px;
x=10;
*px = 20;
Error: Un-initialized pointer. px is pointing to an unknown memory location. Hence it
will overwrite that location’s contents and store 20 in it.
int x, *px;
x=10;
px = x;
Error: It should be px = &x;
7
DATA STRUCTURES AND APPLICATIONS (BCS304)
The process of allocating memory to the variables during execution of the program or
at run time is known as dynamic memory allocation.
C language provides a mechanism of dynamically allocating memory so that only the
amount of memory that is actually required is reserved.
We reserve space only at the run time for the variables that are actually required.
Dynamic memory allocation gives bestperformance in situations in which we do not
know memory requirements in advance.
C language has four library routines which allow thisfunction.
Function Task
malloc() Allocates memory and returns a pointer to the first byte of allocated space
calloc() Allocates space for an array of elements, initializes them to zeroand returns a
pointer to the memory
free() Frees previously allocated memory
realloc() Alters the size of previously allocated memory
1.malloc()
8
DATA STRUCTURES AND APPLICATIONS (BCS304)
#include <stdio.h>
#include <stdlib.h>
int main()
int i, n;
int *arr;
scanf("%d", &n);
if(arr == NULL)
exit(0);
scanf("%d", &arr[i]);
printf("%d", arr[i]);
return 0;
2.calloc()
It is used to request multiple blocks of storage each of the same size and then sets all
bytes to zero.
calloc() stands for contiguous memory allocation and is primarily used to allocate
memory for arrays.
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each of size elem-size bytes.
The difference between malloc() and calloc() is that when we use calloc(), all bytes are
initialized to zero.
When memory is allocated using malloc() or calloc(), a NULL pointer will be returned if
there is not enough space in the system to allocate.
if(ip == NULL)
10
DATA STRUCTURES AND APPLICATIONS (BCS304)
return;
#include <stdio.h>
#include <stdlib.h>
int main ()
int i,n;
int *arr;
scanf("%d",&n);
if (arr==NULL)
exit (1);
scanf ("%d",&arr[i]);
printf ("%d",arr[i]);
free(arr);
return 0;
11
DATA STRUCTURES AND APPLICATIONS (BCS304)
Realloc() is a function that can be used to change the size of memory that was
previously allocated using calloc() or malloc().
The function takes two arguments: a pointer to the memory to be resized and the
new size of the memory.
Realloc() returns a pointer to the resized memory block, or NULL if the request
fails.
If realloc() was able to make the old block of memory bigger, it returns the same
pointer.
Otherwise, realloc() allocates a new block of memory and copies the old data to it.
It is important to check if the pointer returned by realloc() is NULL before using
it.
12
DATA STRUCTURES AND APPLICATIONS (BCS304)
#define NULL 0
int main()
char *str;
if(str==NULL)
exit(1);
strcpy(str,"Hi");
/*Reallocation*/
if(str==NULL)
exit(1);
strcpy(str,"Hi there");
13
DATA STRUCTURES AND APPLICATIONS (BCS304)
/*freeing memory*/
free(str);
return 0;
1.6 Arrays
An array data structure, or simply an array, is a data structure consisting of a
collection of (mainly of similar data types) elements (values or variables), each
identified by at least one array index or key. An array is stored so that the position
of each element can be computed from its index tuple by a mathematical formula.
An array is a collection of items stored at contiguous memory locations.
An array must be declared before being used. Declaring an array means specifying
the following:
1. Data_type—the kind of values it can store, for example, int, char, float,
double.
2. Name—to identify the array.
3. Size—the maximum number of values that the array can hold.
Arrays are declared using the following syntax:
Data_type Name[Size];
The type can be either int, float, double, char, or any other valid data type.
The number within brackets indicates the size of the array, i.e., the maximum
number of elements that can be stored in the array.
For example, if we write, int marks[10]; The above statement declares an array
marks that contains 10 elements. In C, the array index starts from zero. This
means that the array marks will contain 10 elements in all. The first element will
be stored in marks[0], second element in marks[1], so on and so forth.
Therefore, the last element, that is the 10th element, will be stored in
marks[9].
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
eleme eleme eleme eleme eleme eleme eleme eleme eleme eleme
nt nt nt nt nt nt nt nt nt nt
Mark Mark Mark Mark Mark Mark Mark Mark Mark Mark
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
Here, A is the array, k is the index of the element of which we have to calculate
the address, BA is the base address of the array A, and w is the size of one
15
DATA STRUCTURES AND APPLICATIONS (BCS304)
element in memory, for example, size of int is 4 .Ex: Given an array int marks[] =
{99,67,78,56,88,90,34,85}, calculate the address of marks[4] if the base address =
1000.
99 67 78 56 88 90 34 85
Marks[0 Marks[1 Marks[2 Marks[3 Marks[4 Marks[5 Marks[6 Marks[7
] ] ] ] ] ] ] ]
1000 1002 1004 1006 1008 1010 1012 1014
.
marks[4] = 1000 + 4(4 – 0) = 1000 + 4(4) = 1016
or
marks[4]=1000+4*4=1016
16
DATA STRUCTURES AND APPLICATIONS (BCS304)
#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
17
DATA STRUCTURES AND APPLICATIONS (BCS304)
if(n<1)
{ printf(“improper value of n”);
exit(0);
}
list=(int*)malloc(n*sizeof(int));
Now if n<1, it will come out of the program, else, it will create n*4bytes during
run time.i.e, if n=3, we need to generate 3 memory location for integer no’s (12
bytes
1.7.2Two-D Array:
C uses array of array representation to represent a multi-dimensional array.
Normally, a pointer contains the address of a variable. A pointer-to-pointer
contains address of another pointer. When we define a pointer to a pointer, the
first pointer contains the address of the second pointer, which points to the
location that contains the actual value as shown below.
int a; allocates memory for variable ‘a’ where integer can be stored
int *p1; allocates memory for variable ‘p1’ where address of an
integer can be stored
int **p2; allocates a memory for variable ‘p2’ where address of
pointer can be stored
A 2-D array represented as a 1-D array of pointers where each pointer contains
address of 1-D array. ex: int x[3][5]; The figure shows array to array representation,
where each of 3 pointers points to 1-D array consisting of 5 locations
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
18
DATA STRUCTURES AND APPLICATIONS (BCS304)
1.8 Structures
Structure is a user defined data type that can hold data items of different data
types.
The major difference between a structure and an array is that an array can
store only information of same data type.
Syntax
struct{
member1;
19
DATA STRUCTURES AND APPLICATIONS (BCS304)
member2;
…..
member n;
}; structurename
Example
struct {
char name[10];
int age;
float salary;
} person;
The above example creates a structure and variable name is Person and that has
three fields:
name = a name that is a character array
age = an integer value representing the age of the person
salary = a float value representing the salary of the individual
Assign values to fieldsto assign values to the fields, use. (dot) as the structure
member operator. This operator is used to select a particular member of the
structure
Ex: strcpy(Person.name,“james”);
Person.age = 10;
Person.salary = 35000;
1.8.1 Structure Declaration
Structure definition with a tag name-Tagged Structure
Syntax:
Struct structure_name
{ member1;
member2;
…
member n;
};
Example:
struct person
{
20
DATA STRUCTURES AND APPLICATIONS (BCS304)
char name[10];
int age;
float salary;
};
Example1: Program that uses a simple structure to store the student
marks details
#include <stdio.h>
#include <string.h>
struct student
{
char name[20], subject[20];
float percentage;
}s1;
int main()
{
strcpy(s1.name, "aditi");
strcpy(s1.subject, "Maths");
s1.percentage = 91.25;
printf(" Name : %s \n", s1.name);
printf(" Subject : %s \n", s1.subject);
printf(" Percentage : %f \n", s1.percentage);
return 0;
}
Type Defined Structure: We can create our own structure data type by using
typedef statement as:
typedef struct
{
data_type member 1;
data_type member 2;
21
DATA STRUCTURES AND APPLICATIONS (BCS304)
………………………
………………………
data_type member n;
} TypeName;
typedef is the keyword used at the beginning of the definition and by using
typedef user defined data type can be obtained.
struct is the keyword which tells structure is defined to the complier
The members are declared with their data_type
Type_name is not a variable; it is user defined data_type
Method-1:
typedef struct person{
char name[10];
int age;
float salary;
};
person person1, person2;
Method-2:
typedef struct {
char name[10];
int age;
float salary
} person;
person person1, person2;
In above example, person is the name of the type and it is a user defined data
type. Declarations of structure variables: person person1, person2;
This statement declares the variable person1 and person2 are of type person.
Example2:Program that uses a simple structure to store the student marks
details using typedef structure
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[20], subject[20];
float percentage;
22
DATA STRUCTURES AND APPLICATIONS (BCS304)
}students;
int main()
{
students s1;
strcpy(s1.name, "aditi");
strcpy(s1.subject, "Maths");
s1.percentage = 91.25;
printf(" Name : %s \n", s1.name);
printf(" Subject : %s \n", s1.subject);
printf(" Percentage : %f \n", s1.percentage);
return 0;
}
1.9 Unions
Union is a derived data type, like structure, i.e. collection of elements of different data
types which are grouped together. Each element in a union is called member. Union
24
DATA STRUCTURES AND APPLICATIONS (BCS304)
allocates one common storage space for all its members, or memory space is shared
between its members. So only one field of union is active at any given time
Syntax:
Method-1:
union tagname
{
Type1 member1;
Type2 member2;
….
};
Method-2:
typedef union
{
Type1 member1;
Type2 member2;
….
};
Similar to structures, a union is a collection of variables of different data types.
The only difference between a structure and a union is that in case of unions, you
can only store information in one field at any one time.
To better understand a union, think of it as a chunk of memory that is used to
store variables of different types. When a new value is assigned to a field, the
existing data is replaced with the new data.
Thus, unions are used to save memory. They are useful for applications that
involve multiple members, where values need not be assigned to all the members
at any one time. Table below shows the difference between structures and unions.
Basis of
Structure Union
comparison
The separate memory location is allotted All members of the 'union'
Basic to each member of the 'structure'. share the same memory
location.
struct struct_name{ union u_name{
type element1; type element1;
Declaration type element2; type element2;
…. ….
} variable1, variable2, ...; } variable1, variable2, ...;
Keyword 'struct' 'union'
25
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example
#include <stdio.h>
#include <string.h>
union student
{
char name[20], subject[20];
float percentage;
}s1;
int main()
{
strcpy(s1.name, "aditi");
strcpy(s1.subject, "Maths");
s1.percentage = 91.25;
printf(" Name : %s \n", s1.name);
printf(" Subject : %s \n", s1.subject);
printf(" Percentage : %f \n", s1.percentage);
return 0;
}
26
DATA STRUCTURES AND APPLICATIONS (BCS304)
For example, consider the structure node given below. Here, the structure node
will contain two types of data: a character data and a pointer link. The value of
link is either the address in the memory of an instance of a list or the null pointer.
Consider these statements which create 3 structures and assign values to their
respective fields:
27
DATA STRUCTURES AND APPLICATIONS (BCS304)
1.11 Polynomials
A polynomial is a sum of terms, where each term has a formaxe,Where x=variable,
a=coefficient and e=exponent.
For ex,A(x)=3x20+2x5+4 and B(x)=x4+10x3+3x2+1.The largest (or leading)
exponent of a polynomial is called its degree.
Assume that we have 2 polynomials, A(x)= ∑ai x i& B(x)= ∑bi xi,then A(x)+B(x)=
∑ (ai + bi) xii.e the above sum would be S(x)=3x20+2x5+ x4+10x3+3x2+5
A polynomial thus may be represented using arrays or linked lists.If any term is not
present, then we assign 0’s in the corresponding coefficient.
A structure may be defined such that it contains two parts- one is the coefficient and
second is the corresponding degree.Given below is the polynomial representation
using structure.
#define max_degree 100
typedef struct
{
float coef[max_degree];
int degree;
}polynomial;
Array of Structure:Instead of using one array for each polynomial, we use one
array to store all polynomials, which saves space
25x6+10x5+7x2+9
15x6+5x4+4x3
c=40 x6+………
Case 2:Power of Polynomial a is Greater than Power of Polynomial b
Remaining polynomial is: a =10x5+7x2+9 lead exponent(a)=5
b = 5x4+4x3 lead exponent(b)=4
so, lead exponent(a)>lead exponent(b). so copy lead exponent(a) directly to c
sum is,
10x5+7x2+9
5x4+4x3
c=10 x5+………
Case 3: Power of Polynomial a is Less than Power of Polynomial b
Remaining polynomial is: a =7x2+9 lead exponent(a)=2
b = 5x4+4x3 lead exponent(b)=4
so, lead exponent(a)<lead exponent(b). so copy lead exponent(b) directly to c
sum is,
7x2+9
5x4+4x3
c=5x4+………
so final polynomial is: 40x6+10x5+5x4+4x3 +7x2+9
Coding:
/* d =a + b, where a, b, and d are polynomials */
d = Zero( )
while (! IsZero(a) && ! IsZero(b)) do {
switch COMPARE (Lead_Exp(a), Lead_Exp(b)) {
case -1: d = Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b));
b = Remove(b, Lead_Exp(b));
break;
case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b));
if (sum) {
Attach (d, sum, Lead_Exp(a));
a = Remove(a , Lead_Exp(a));
b = Remove(b , Lead_Exp(b));
29
DATA STRUCTURES AND APPLICATIONS (BCS304)
}
break;
case 1: d = Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a));
a = Remove(a, Lead_Exp(a));
}
}
insert any remaining terms of a or b into d
Triplet Representation
#define max 101
typedefstruct
{
int col, row,val;
30
DATA STRUCTURES AND APPLICATIONS (BCS304)
}term;
term a[max];
In this representation, we consider only non-zero values along with their row and
column index values. Each non zero value is a triplet of the form <R,C,Value>
where R represents the row in which the value appears, C represents the column in
which the value appears and Value represents the nonzero value itself. In this
representation, the 0th row stores total rows, total columns and total non-zero
values in the matrix.For example, consider a matrix of size 5 X 6 containing 6
number of non-zero values. This matrix can be represented as shown in the fig.
In above example matrix, there are only 6 non-zero elements (those are 9, 8, 4, 2,
5 & 2) and matrix size is 5 X 6. We represent this matrix as shown in the above
image. Here the first row in the right side table is filled with values 5, 6 & 6 which
indicate that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values.
Second row is filled with 0, 4, & 9 which indicates the value in the matrix at 0th
row, 4th column is 9. In the same way the remaining non-zero values also follows
the similar pattern.
To transpose a matrix we just interchange the rows and columns. This means
that each element a[i][j] in the original matrix becomes b[j][i] in the transpose
matrix (Fig 2.11).
31
DATA STRUCTURES AND APPLICATIONS (BCS304)
Fast Transpose:
Create a much better algorithm by using a little more storage.
Transpose of a matrix can be represented as a sequence of triples in O{columns +
elements) time.
Fast-transpose proceeds by first determining the number of elements in each column
of the original matrix.
This gives us the number of elements in each row of the transpose matrix. From this
information, we can determine the starting
position of each row in the transpose matrix. We now can move the elements in the
origi
nal matrix one by one into their correct position in the transpose matrix.
32
DATA STRUCTURES AND APPLICATIONS (BCS304)
33
DATA STRUCTURES AND APPLICATIONS (BCS304)
Consider the sparse matrix used in the Triplet representation. This sparse matrix
can be represented using linked representation as shown in the below image. In
this representation, H0, H1..., H5 indicates the header nodes which are used to
represent indexes. Remaining nodes are used to represent non-zero elements in the
matrix, except the very first node which is used to represent abstract information
of the sparse matrix (i.e., It is a matrix of 5 X 6 with 6 non-zero elements). In this
representation, in each row and column, the last node right field points to its
respective header node in the above figure.
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
1.14 Strings
35
DATA STRUCTURES AND APPLICATIONS (BCS304)
Pattern Matching:
Knuth, Morris, and Pratt have developed a pattern matching algorithm that has linear
complexity. Using the example, suppose
pat = 'abcabcacab’
Let s = so s2 • • • sm-1 be the string and assume that we are currently determining
whether or not there is a match beginning at si. If s≠a then, clearly, we may proceed by
comparing si+1 and a. Similarly if si= a and si+1≠b then we may proceed by compar
36
DATA STRUCTURES AND APPLICATIONS (BCS304)
we may continue the search for a match by comparing the first character in pat with Si+2
We observe that the search for a match can proceed by comparing Si+4 and the second
character in pat, b. This is the first place a partial match can occur by sliding the
patternpat towards the right. Thus, by knowing the characters in the patterm and the
position in the pattern where a mismatch occurs with a character in 5 we can determine
where in thepattern to continue the search for a match without moving backwards in 5. To
formalizethis, we define a failure function for a pattern.
37
DATA STRUCTURES AND APPLICATIONS (BCS304)
38
DATA STRUCTURES AND APPLICATIONS (BCS304)
1.15 STACK
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).
A stack is an ordered list in which all topmost plate first. Hence, you can
insertions and deletions are made at add and remove an element (i.e., a
one end, called the top. Hence, a plate) only at/from one position
stack is called a LIFO (Last-In-First- which is the topmost position.
Out) data structure, as the element
that was inserted last is the first one
to be taken out.
For example, a pile of plates where
one plate is placed on top of another
(Fig 1). Now, when you want to
Fig. 1: Example for Stack of Plate
remove a plate, you remove the
39
DATA STRUCTURES AND APPLICATIONS (BCS304)
Stack Operations
Various operations in stack are:
1. Push: Element is inserted into the top of stack using push operation.
2. Pop: Element is deleted from the top of stack using pop operation.
3. Overflow: checks if the stack is full or not.
4. Underflow: checks if the stack is empty or not.
top = top+1;
Now insert the item 10 into that position.
stack[top]=item;
DATA STRUCTURES AND APPLICATIONS (BCS304)
To insert next element, top needs to be incremented once again and insert the
element.
We can repeat the same operation until stack is full. Now if we try to push one
more element say 6, it is not possible, since stack is full.
This situation is called stack overflow. i.e. when the stack is full and if we try
to insert one more new element into stack, then it becomes stack overflow
(fig.5).
{
int i;
if(top==-1)
printf("\n Sorry Empty Stack");
else
{
printf("\nThe elements of the stack are\n");
for(i=top;i>=0;i--)
printf("stack[%d] = %d\n",i, stack[i]);
}
}}
1.15.1 Stacks using Dynamic Arrays.
The array is used to implement stack, but the bound (MAX_STACK_ SIZE)
should be known during compile time.
The size of bound is impossible to alter during compilation hence this can be
overcome by using dynamically allocated array for the elements and then
increasing the size of array as needed.
}
5. pop( ): In this function, no changes are made.
element pop ( ){ /* delete and return the top element from the stack */
if (top == -1)
return stackEmpty(); /* returns an error key */
return stack[top--];
}
6. stackFull( ): The new code shown below, attempts to increase the capacity of the
array stack so that new element can be added into the stack. Before increasing the
capacity of an array, decide what the new capacity should be. In array doubling, array
capacity is doubled whenever it becomes necessary to increase the capacity of an
array.
void stackFull()
{
REALLOC (stack, 2*capacity*sizeof(*stack));
capacity *= 2;
}
1.15.3 Evaluation and conversion of Expressions
An algebraic expression is a legal combination of operators and operands.
Operand is the quantity on which a mathematical operation is performed. Operand
may be a variable like x,y, z or a constant like 5, 4, 6 etc.
Operator is a symbol which signifies a mathematical or logical operation between
the operands.Examples of familiar operators include +, -, *, /, ^ etc.An algebraic
expression can be represented using three different notations. They are
1. Infix Expression:In this expression, the binary operator is placed in-between the
operand. Example is shown in Fig 6(a).
2. Prefix notations (Polish notation): In this expression, the operator appears before its
operand.Example is shown in Fig 6(b).
3. Postfix (Reverse Polish notation): In this expression, the operator appears after its
operand.Example is shown in Fig 6(c).
/=, %=
, Comma operator 1 LR
Algorithm:
o If the precedence and associativity of the scanned operator are greater than
the precedence and associativity of the operator in the stack, then push it in
the stack.
Check for a condition when the operator at the top of the stack and
the scanned operator both are ‘^‘. In this condition, the precedence
of the scanned operator is higher due to its right associativity. So it
will be pushed into the operator stack.
In all the other cases when the top of the operator stack is the same
as the scanned operator, then pop the operator from the stack
because of left associativity due to which the scanned operator has
less precedence.
o Else, Pop all the operators from the stack which are greater than or equal
to in precedence than that of the scanned operator.
5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
7. Once the scanning is over, Pop the stack and add the operators in the postfix
expression until it is not empty.
Example:
1st Step: Here i = 0 and exp[i] = ‘a’ i.e., an operand. So add this in the postfix
expression. Therefore, postfix = “a”.
2nd Step: Here i = 1 and exp[i] = ‘+’ i.e., an operator. Push this into the stack. postfix =
“a” and stack = {+}.
3rd Step: Now i = 2 and exp[i] = ‘b’ i.e., an operand. So add this in the postfix
expression. postfix = “ab” and stack = {+}.
DATA STRUCTURES AND APPLICATIONS (BCS304)
4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix =
“ab” and stack = {+, *}.
5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression.
postfix = “abc” and stack = {+, *}.
DATA STRUCTURES AND APPLICATIONS (BCS304)
6th Step: Now i = 5 and exp[i] = ‘+’ i.e., an operator. The topmost element of the stack
has higher precedence. So pop until the stack becomes empty or the top element has less
precedence. ‘*’ is popped and added in postfix. So postfix = “abc*” and stack = {+}.
Now top element is ‘+‘ that also doesn’t have less precedence. Pop it. postfix =
“abc*+”.
DATA STRUCTURES AND APPLICATIONS (BCS304)
7th Step: Now i = 6 and exp[i] = ‘d’ i.e., an operand. Add this in the postfix expression.
postfix = “abc*+d”.
DATA STRUCTURES AND APPLICATIONS (BCS304)
Final Step: Now no element is left. So empty the stack and add it in the postfix
expression. postfix = “abc*+d+”.
( (
A ( A
- (- A
( (-( A
B (-( AB
/ (-(/ AB
C (-(/ ABC
+ (-(+ ABC/
( (-(+( ABC/
D (-(+( ABC/D
% (-(+(% ABC/D
E (-(+(% ABC/DE
* (-(+(* ABC/DE%
F (-(+(* ABC/DE%F
) (-(+ ABC/DE%F*
/ (-(+/ ABC/DE%F*
G (-(+/ ABC/DE%F*G
) (- ABC/DE%F*G/+
* (-* ABC/DE%F*G/+
H (-* ABC/DE%F*G/+H
) ABC/DE%F*G/+H*-
#include<stdio.h>
void infix_to_postfix();
void push(char);
char pop();
int priority(char);
char infix[30], postfix[30],stack[30];
int top=-1;
void main()
{
printf("Enter the valid Infix expression \n");
scanf("%s",infix);
infix_to_postfix();
printf("\n Infix expression : %s",infix);
printf("\n Postfix expression : %s\n",postfix);
}
case '+':
case '-': p=1;
break;
case '*':
case '/':
case '%': p=2;
break;
case '^':
case '$': p=3;
break;
case '(':
case ')': p=0;
break;
case '#': p=-1;
break;
} // end of switch
return p;
} // end of function priority
postfix[j++]=temp;
temp=pop();
} // end of while
break;
case'+':
case'-':
case'*':
case'/':
case'%':
case'^':
case'$': while(priority(stack[top])>=priority(symb)) // check for priority of
operator
{
temp=pop();
postfix[j++]=temp;
}
push(symb);
break;
default: postfix[j++]=symb;
} // end of switch
} // end of for
while(top>0) // pop remaining all symbols form top of stack and store to
postfix
{
temp=pop();
postfix[j++]=temp;
} // end of while
postfix[j]='\0'; // end string postfix
} // end of function infix_to_postfix
DATA STRUCTURES AND APPLICATIONS (21CS32)
Problem 1: Evaluate the following postfix expression FOR A=1, B=2 and C=3:
ABC+*CBA-+*
Solution:given in Table 1.The above expression can be written as 123+*321-+*
Table 1: Solution for Problem 1.
Postfix Expression Symbol Scanned Op2 Op1 Res = Op1 Op Op2 Stack
123+*321-+* 1 1
23+*321-+* 2 1,2
3+*321-+* 3 1,2,3
+*321-+* + 3 2 2+3=5 1,5
*321-+* * 5 1 1*5=5 5
321-+* 3 5,3
21-+* 2 5,3,2
1-+* 1 5,3,2,1
-+* - 1 2 2-1=1 5,3,1
+* + 1 3 3+1=4 5,4
57
DATA STRUCTURES AND APPLICATIONS (21CS32)
* * 4 5 5*4=20 20
Problem 2: Evaluate the following postfix expression FOR A=1, B=2 and C=3:
AB+C-BA+C^-
Solution:given in Table 2.The above expression can be written as 12+3-21+3^-
Table 2: Solution for Problem 2.
Postfix Expression Symbol Scanned Op2 Op1 Res = Op1 Op Op2 Stack
12+3-21+3^- 1 1
2+3-21+3^- 2 1,2
+3-21+3^- + 2 1 1+2=3 3
3-21+3^- 3 3,3
-21+3^- - 3 3 3-3=0 0
21+3^- 2 0,2
1+3^- 1 0,2,1
+3^- + 1 2 2+1=3 0,3
3^- 3 0,3,3
^- ^ 3 3 3^3=27 0,27
- - 27 0 0-27=-27 -27
Problem 3: Convert the following infix expression to postfix expression and evaluate the
postfix expression FOR A=6, B=3, C=1,D=2, E=4: A/B-C+D*E-A*C
Solution:Fully parenthesized expression is: ((((A/B)-C)+(D*E))-(A*C)). Refer table 3 for
conversion of infix to postfix expression. We get AB/C-DE*+AC*- as postfix expression. Now to
evaluate this postfix expression, refer table 4.10. When we assign the given values to the postfix
expression, we get: 63/1-24*+61*-.
Table 3: Solution for Problem 3.
Postfix Expression Symbol Scanned Op2 Op1 Res = Op1 Op Op2 Stack
63/1-24*+61*- 6 6
3/1-24*+61*- 3 6,3
/1-24*+61*- / 3 6 6/3=2 2
1-24*+61*- 1 2,1
-24*+61*- - 1 2 2-1=1 1
24*+61*- 2 1,2
4*+61*- 4 1,2,4
*+61*- * 4 2 2*4=8 1,8
+61*- + 8 1 1+8=9 9
61*- 6 9,6
1*- 1 9,6,1
*- * 1 6 6*1=6 9,6
- - 6 9 9-6=3 3
58
DATA STRUCTURES AND APPLICATIONS (21CS32)
/* .Design, Develop and Implement a Program in C for the following Stack Applications
To Evaluate the postfix expression with single digit operands and operators: +, -, *, /, %, ^*/
#include<stdio.h>
#include<math.h>
void push(float);
float pop();
void evaluate(char[]);
float stack[20];
int top=-1;
void main()
{
int choice,n;
char postfix[100];
while(1) // infinate loop for menu
{
printf("\n STACK APPLICATIONS");
printf("\n Enter your Choice: ");
printf("\n 1. Evaluation of postfix expression with single digit operands and operators");
printf("\n 2. Exit \n");
scanf("%d", &choice);
switch(choice)
{
case 1 : printf("Enter a valid postfix expression\n");
scanf("%s",postfix);
evaluate(postfix);
break;
case 2 : return;
default : printf("\n Invalid Choice");
} // end of switch
} // end of menu
} // end of main
59
DATA STRUCTURES AND APPLICATIONS (21CS32)
{
stack[++top]=item;
} // end of push
60
DATA STRUCTURES AND APPLICATIONS (21CS32)
case '*':op2=pop();
op1=pop();
res=op1*op2;
push(res);
break;
case '/':op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero Error\n");
return;
}
res=op1/op2;
push(res);
break;
case '%': op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero Error\n");
return;
}
res=(int)op1%(int)op2;
push(res);
break;
case '^':op2=pop();
op1=pop();
res=pow(op1,op2);
push(res);
break;
}// end of switch
} // end of for
res=pop(); // pop the final answer from top of stack
if(top==-1)
61
DATA STRUCTURES AND APPLICATIONS (21CS32)
Question Bank
1. Define data structures
2. Explain classifications of data structures
3. Explain the different operations of data structures
4. Define structures. Explain different types of structure declaration and initialization
5. Write the difference between structures and union
6. Explain pointers with an example
7. What are pointer variables? How to declare a pointer variable?
8. Define a pointer. Write a C function to swap two numbers using pointers.
9. Explain self-referential structures
10. Define array and explain with an example
11. What are the different operations of array? Explain
12. Explain multi-dimensional array
13. Explain sparse matrix and its representation
14. Explain with example the functions supported by C to carryout dynamic memory allocation
15. What are the various memory allocation techniques? Explain how memory can be dynamically
allocated using malloc().
16. Write the difference between malloc and calloc
17. Explain how the 2-D array can be created dynamically
18. Develop a structure to represent a solar system. Each planet has 3 fields - name, distance from
sun, no of moons. Write a program to read the data for each planet and store. Also print the
name of the planets that has the highest number of moons.
19. What is a polynomial? What is the degree of a polynomial? Write a function to add two
polynomials.
20. Define structure and unions with example.
62
DATA STRUCTURES AND APPLICATIONS (21CS32)
21. Write a C program with suitable structure definition and variable declaration to store
information about employee. Consider the following fields: Ename, EID, DOJ(Date, month,
year), and salary (basic, DA, HRA).
22. Write a C program for demonstrating all array operations.
23. For the given sparse matrix and its transpose, give the triplet representation using one
dimensional array.
24. Consider two polynomials A(x)=2x1000+1 and B(x)=x4+10x3+3x2+1 with a diagram show how
these two polynomials are stored using 1D array and also give its C representation.
25. Define stack. Give the C implementation of push, pop, overflow and underflow functions for
stack using arrays.
26. Define stack. List the operation on stack.
27. Obtain postfix expression for ((( A+(B-C)*D)^E)+F).
28. Write the postfix form of the following expression.
i.(a+b)*d+e/(f+a*d)+c
ii.((a/(b-c+d))*(e-a)*c)
iii.a/b-c+d*e-a*c
29. Write an algorithm to convert infix to postfix expression and apply the same to convert the
following expression from infix to postfix :
i)(a * b) +c/d
ii) (((a/b)-c) + (d * e)) – (a * c).
30. Convert the infix expression (((a/b)-c) + (d * e)) – (a * c) into postfix expression. Write a
function to evaluate that postfix expression and trace for the data: a=6, b=3, c=1, d=2, e=4
31. Write an algorithm to convert infix to postfix expression and trace it for the expression
a * (b +c)*d
63