Module 1
Module 1
Module 1- Introduction
Module 1 Syllabus INTRODUCTION TO DATA
STRUCTURES: Data Structures,
Classifications (Primitive&
Non-Primitive), 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
1
DATA STRUCTURES AND APPLICATIONS (BCS304)
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
2
DATA STRUCTURES AND APPLICATIONS (BCS304)
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.
3
DATA STRUCTURES AND APPLICATIONS (BCS304)
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.
∙ The relationship of adjacency is not maintained between elements of a non-linear
data structure.
∙ This structure is mainly used to represent data containing a hierarchical relationship
between elements.
∙ Examples include trees and graphs.
1. A graph is a non-linear data structure which is a collection of vertices (also
called nodes) and edges that connect these vertices. A graph is often viewed as a
generalization of the tree structure, where instead of a purely parent-to-child
relationship between tree nodes, any kind of complex relationships between the
nodes can exist.
Review Questions:
1. What is data structure?
2. What is linear data structure?
3. What is non primitive data structure?
4. What are applications of data structure?
4
DATA STRUCTURES AND APPLICATIONS (BCS304)
5
DATA STRUCTURES AND APPLICATIONS (BCS304)
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).
6
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ 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() {
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.
7
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ 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;
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
8
DATA STRUCTURES AND APPLICATIONS (BCS304)
1.malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, n;
int *arr;
printf("\n Enter the number of elements ");
scanf("%d", &n);
if (arr == NULL) {
exit(0);
scanf("%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.
10
DATA STRUCTURES AND APPLICATIONS (BCS304)
if(ip == NULL)
return;
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, n;
int *arr;
scanf("%d", &n);
free(arr);
return 0;
11
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ Dynamically allocated memory must be manually released using the free() function.
∙ Releasing unused memory is crucial for efficient memory management, especially when
storage space is limited.
∙ The free() function takes a pointer as an argument and returns the memory block pointed
to by that pointer to the free list within the heap.
∙ The pointer passed to free() must have been previously allocated using malloc() or
calloc().
4.realloc()- To
Alter the Size of Allocated Memory
∙ 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)
The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.
malloc () doesn‟t initializes the allocated calloc () initializes the allocated memory
memory. It contains garbage values to zero
Syntax Syntax
variable_name=(datatype*)malloc(sizeof variable_name=(datatype*)calloc(n,size);
(
13
DATA STRUCTURES AND APPLICATIONS (BCS304)
datatype));
Review Questions:
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.
14
DATA STRUCTURES AND APPLICATIONS (BCS304)
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
Mar Mar Mar Mar Mar Mar Mar Mar Mar Mar
k s[0] k s[1] k s[2] k s[3] k s[4] k s[5] k s[6] k s[7] k s[8] k 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 element in
memory, for example, size of int is 4 .Ex: Given an array int marks[] =
15
DATA STRUCTURES AND APPLICATIONS (BCS304)
99 67 78 56 88 90 34 85
Marks[ Marks[ Marks[ Marks[ Marks[ Marks[ Marks[
Marks[
1] 2] 3] 4] 5] 6] 7]
0]
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;
}
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() {
int row = 2, col = 3;
int *arr = (int *)malloc(row * col * sizeof(int));
18
DATA STRUCTURES AND APPLICATIONS (BCS304)
int i, j;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++) *(arr + i + j) = i + j;
printf("The matrix elements are:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", *(arr + i + j));
}
printf("\n");
}
free(arr);
return 0;
}
Review Questions:
1. What is an array ?
2. What are the applications of arrays?
3. What is the application of 2D array?
4. How many loops are required for defining 3D arrays?
5. What is the method to calculate index of array?
19
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ The major difference between a structure and an array is that an array can store
only information of same data type.
Syntax
struct{
member1;
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;
20
DATA STRUCTURES AND APPLICATIONS (BCS304)
};
Example:
struct person
{
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;
}
21
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ 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;
………………………
………………………
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
22
DATA STRUCTURES AND APPLICATIONS (BCS304)
#include <stdio.h>
#include <string.h>
typedef struct {
char name[20], subject[20];
float percentage;
} 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;
}
Example3:Program that uses a simple structure to store the student details.
#include <stdio.h>
struct student {
char name[30];
int rollno;
int t_marks;
};
void main() {
int num, i;
23
DATA STRUCTURES AND APPLICATIONS (BCS304)
24
DATA STRUCTURES AND APPLICATIONS (BCS304)
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
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
{
25
DATA STRUCTURES AND APPLICATIONS (BCS304)
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.
Store Value Stores distinct values for all the members. Stores same value for all
the members.
∙ Example
#include <stdio.h>
#include <string.h>
union student {
char name[20], subject[20];
float percentage;
} s1;
26
DATA STRUCTURES AND APPLICATIONS (BCS304)
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;
}
∙ Consider these statements which create 3 structures and assign values to their respective
fields:
27
DATA STRUCTURES AND APPLICATIONS (BCS304)
item1.link=item2.link=item3.link=NULL;
∙ Structures item1, item2 and item3 each contains the data item a, b and c and the null
pointer. We can attach these structures together by replacing the null link field in
item 2 with one that points to item 3 and by replacing the null link field in item 1
with one that points to item2.
item1.link=&item2;
item2.link=&item3;
Review Questions:
1. What is a structure?
2. What is an instance of structure?
3. What is self-referential structure?
4. What is union?
5. Differentiate between structure and union?
28
DATA STRUCTURES AND APPLICATIONS (BCS304)
sum is,
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+4x3lead 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+4x3lead 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));
30
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;
31
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).
32
DATA STRUCTURES AND APPLICATIONS (BCS304)
33
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ In linked representation, we use linked list data structure to represent a sparse
matrix. In this linked list, we use two different nodes namely header node and
element node. Header node consists of three fields and element node consists of
five fields as shown in the fig.
34
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.
Review Questions:
1. What is a polynomial?
2. When do we add two polynomials?
3. What is the condition to be checked before we perform polynomial
addition?
4. What is sparse matrix?
5. What are the two representations of sparse matrices?
6. What is fast transpose?
int arr[3][3], i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("Enter a[%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf("%d\t", arr[i][j]);
}
}
}
1.14 Strings
36
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
37
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.
KMP (
Knuth Morris Pratt) Algorithm:
38
DATA STRUCTURES AND APPLICATIONS (BCS304)
Computing Failure function:
39
DATA STRUCTURES AND APPLICATIONS (BCS304)
Review Questions:
40
DATA STRUCTURES AND APPLICATIONS (BCS304)
∙ If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then
the stack is full. (Since array indices start from 0, it is MAX-1, instead of MAX).
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.
Fig. 3: Stack operations
a. Stack Create
It creates stack stack[] with size MAX (here defined as 5)
#define MAX 5
∙ The element can be inserted only from one end of the stack called top of stack.
Initially as we know that top will be pointing to -1. This is called empty stack.
DATA STRUCTURES AND APPLICATIONS (BCS304)
top = top+1;
∙ 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).
printf("\n\nStack is Overflow");
}
else
{ top=top+1;
stack[top] = item;
}
c. Pop and Stack Underflow
∙ Deleting an element from the stack is called pop operation. Only one
element can be deleted at a time and it is from the top of the stack. ∙
Element 5 is at top most position and needs to be deleted first. Then the
pointer top needs to be pointed to previous position. When the top points
to -1, which means there is no element in the stack. When we try to delete
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.
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;
}
Review Questions:
1. What is a stack?
2. Where is top initially pointing to?
3. What is stack overflow?
4. What is stack underflow?
5. Which data structure is used to implement stack?
3. Postfix (Reverse Polish notation): In this expression, the operator appears after its
operand.Example is shown in Fig 6(c).
^ Power 17 R🡪L
$ Dollar
| Bitwise OR 6 L🡪R
|| Logical OR 4 L🡪R
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.
DATA STRUCTURES AND APPLICATIONS (BCS304)
▪ Inall 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 = {+}.
DATA STRUCTURES AND APPLICATIONS (BCS304)
Push ‘+’ in the 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 = {+}.
4th Step: Now i = 3 and exp[i] = ‘*’ i.e., an operator. Push this into the stack. postfix =
“ab” and stack = {+, *}.
DATA STRUCTURES AND APPLICATIONS (BCS304)
Push ‘*’ in the stack
5th Step: Now i = 4 and exp[i] = ‘c’ i.e., an operand. Add this in the postfix expression.
postfix = “abc” and stack = {+, *}.
( (
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*-
( (
( ((
( (((
A ((( A
+ (((+ A
( (((+( A
B (((+( AB
- (((+(- AB
C (((+(- ABC
) (((+ ABC-
* (((+* ABC
D (((+* ABC-D
) (( ABC-D*+
^ ((^ ABC-D*+
E ((^ ABC-D*+E
) ( ABC-D*+E^
+ (+ ABC-D*+E^
F (+ ABC-D*+E^F
) ABC-D*+E^F+
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); }
DATA STRUCTURES AND APPLICATIONS (BCS304)
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-+* * 5 1 1*5=5 5
321-+* 3 5,3
21-+* 2 5,3,2
1-+* 1 5,3,2,1
+* + 1 3 3+1=4 5,4
59
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^- 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*- + 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
60
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 <math.h>
#include <stdio.h>
void push(float);
float pop();
void evaluate(char[]);
float stack[20];
int choice, n;
char postfix[100];
printf(
"and operators");
scanf("%d", &choice);
switch (choice) {
case 1:
61
DATA STRUCTURES AND APPLICATIONS (21CS32)
scanf("%s", postfix);
evaluate(postfix);
break;
case 2:
return;
default:
} // end of menu
} // end of main
// -, *, /, %, ^
int i;
char symb;
62
DATA STRUCTURES AND APPLICATIONS (21CS32)
symb = postfix[i];
case '+':
op2 = pop();
op1 = pop();
push(res);
break;
case '-':
op2 = pop();
op1 = pop();
push(res);
break;
case '*':
op2 = pop();
op1 = pop();
push(res);
break;
63
DATA STRUCTURES AND APPLICATIONS (21CS32)
case '/':
op2 = pop();
op1 = pop();
if (op2 == 0) {
push(res);
break;
case '%':
op2 = pop();
op1 = pop();
if (op2 == 0) {
break;
case '^':
op2 = pop();
op1 = pop();
push(res);
64
DATA STRUCTURES AND APPLICATIONS (21CS32)
break;
} // end of switch
} // end of for
res = pop(); // pop the final answer from top of stack
if (top == -1)
printf("\n Result: %f\n ", res); // Display the final answer else
top = -1;
Review Questions:
65
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.
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.
66
DATA STRUCTURES AND APPLICATIONS (21CS32)
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
67