BCS304- Data Structures and its Applications
MODULE-1: INTRODUCTION TO DATA STRUCTURES
1. Define data structures. With a neat diagram, explain the classification of data structures
with examples.
Answer:
Definition: Data structures are specialized formats for organizing, processing, and storing
data in a computer so that it can be accessed and modified efficiently. They are fundamental
to designing algorithms and help in managing large amounts of data effectively.
Classification of Data Structures: Data structures can be classified in several ways, but the
two primary classifications are:
i. Primitive Data Structures
ii. Non-Primitive Data Structures
Primitive Data Structures: These are basic data types provided by programminglanguages.
Examples include:
Integer: Represents whole numbers (e.g., int in C/C++)
Float: Represents decimal numbers (e.g., float in C/C++)
Character: Represents single characters (e.g., char in C/C++)
Boolean: Represents true or false values (e.g., bool in C/C++)
Non-Primitive Data Structures: These are more complex structures built using primitive
data types. They can be further classified into:
i. Linear Data Structures
ii.Non Linear Data Structures
Linear Data Structures: Data elements are arranged in a sequential manner.
Arrays: Collection of items stored at contiguous memory locations.
Linked Lists: A collection of nodes where each node contains data and a reference to the
next node.
Stacks: A collection that follows the Last in First out (LIFO) principle.
Queues: A collection that follows the First in First out (FIFO) principle.
YIT, Moodbidri Page 1
BCS304- Data Structures and its Applications
Non-Linear Data Structures: Data elements are not arranged sequentially.
Trees: A hierarchical structure with nodes connected by edges (e.g., binary trees, AVL
trees).
Graphs: A collection of nodes connected by edges (e.g., directed graphs, undirected
graphs).
Examples
Array: [10, 20, 30, 40]
Linked List: 10 -> 20 -> 30 -> NULL
Stack: Top -> 30, 20, 10
Queue: Front -> 10, 20, 30 -> Rear
Tree
Below Diagram shows the classification of Data Structures:
YIT, Moodbidri Page 2
BCS304- Data Structures and its Applications
2. What are the primitive operations that can be performed on Data Structures?
Answer: Primitive operations on data structures typically refer to the basic operations that can be
performed to manipulate and access the data. These operations can vary depending on the type of
data structure, but here are some common primitive operations applicable to many data
structures:
1. Creation: Initialize or create an instance of the data structure.
2. Insertion: Add an element to the data structure.
3. Deletion: Remove an element from the data structure.
4. Traversal: Access or iterate through the elements of the data structure.
5. Search: Find a specific element within the data structure.
6. Update: Modify an existing element in the data structure.
7. Access: Retrieve an element by its position or key.
8. Size: Determine the number of elements currently stored in the data structure.
These operations form the foundation for more complex operations and algorithms that can be
built on top of various data structures, such as arrays, linked lists, stacks, queues, trees, and
graphs.
---------------------------------------------------------------------------------------------------------------------
3. Differentiate between structure and union?
Answer:
Descriptions Structure Union
Memory Allocation Each member of a structure All members share the same
has its own memory memory location. The size of
allocation. The total size of a a union is determined by the
structure is the sum of the size of its largest member. At
sizes of all its members, any given time, a union can
possibly plus padding for hold a value for only one of its
alignment. members.
Declaration Declared using the struct Declared using the union
keyword. keyword.
struct Person { union Data {
char name[50]; intintValue;
float floatValue;
YIT, Moodbidri Page 3
BCS304- Data Structures and its Applications
int age; char charValue;
}; };
Use Case Suitable for grouping related Useful when you want to save
but different types of data memory and need to store
where each member needs to different types of data at
store distinct values. different times, but only one
type will be used at any given
time.
---------------------------------------------------------------------------------------------------------------------
4. Explain in brief the different functions of dynamic memory allocation?
Answer:
Dynamic memory allocation allows programs to request memory at runtime, providing flexibility
for data structures and storage or Dynamic memory functions are used to allocate the memory
during runtime. Here are the key functions commonly used for dynamic memory allocation in C
malloc(): Purpose: Allocates a specified number of bytes of memory.
Usage: Returns a pointer to the beginning of the allocated memory block. The memory is
uninitialized.
Syntax:ptr = ( castType*) malloc( 10 *sizeof(castType));
Example:
int *arr = (int *)malloc(10 * sizeof(int));
calloc(): Purpose: Allocates contiguous block of memory or Allocates memory for an array of
elements and initializes all bytes to zero.Usage: Takes two parameters: the number of elements
and the size of each element.
Syntax:ptr = ( castType*) calloc( n, sizeof(castType));
Example:
int *arr = (int *)calloc(10,sizeof(int));
realloc():Purpose: Resizes previously allocated memory.Usage: Can increase or decrease the
size of the memory block. It may also move the block to a new location if necessary.
Example : *arr = (int *)realloc(arr, 20 * sizeof(int));
YIT, Moodbidri Page 4
BCS304- Data Structures and its Applications
free(): Purpose: Deallocates previously allocated memory. Usage: Releases the memory back to
the system, preventing memory leaks.
Example:free(arr);
---------------------------------------------------------------------------------------------------------------------
5. Define sparse matrix? How to represent a sparse matrix? Write an algorithm to find the
transpose of sparse matrix?
Answer:
Sparse Matrix: Sparse matrix is a matrix in which it contains more number of zero entries and
less number of non-zero entries.
Representation of Sparse Matrix:
1. Array representation
2. Linked list representation
Method 1: Using Arrays:
2D array is used to represent a sparse matrix in which there are three rows named as
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non-zero element located at index – (row,column)
Example:
Row Co Val
0 18 22 l
A= 5 0 0 A[0] 3 3 6
9 1 6 A[1] 0 1 18
A[2] 0 2 22
A[3] 1 0 5
A[4] 1 0 9
A[5] 1 1 1
A[6] 1 2 6
Method 2: Using Linked Lists
In linked list, each node has four fields. These four fields are defined as:
YIT, Moodbidri Page 5
BCS304- Data Structures and its Applications
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index – (row,column)
Next node: Address of the next node
Example:
0 18 22
5 0 0
9 1 6
Linked List representation:
Write the Algorithm for Transpose of the sparse matrix : Refer PPT
-------------------------------------------------------------------------------------------------------------------------------
6. Define sparse matrix? Write the fast transpose algorithm for sparse matrix and write the triple
transpose of the given sparse matrix?
0 18 22
A= 5 0 0
9 1 6
Answer:
Sparse Matrix: Sparse matrix is a matrix in which it contains more number of zero entries and
less number of non-zero entries.
Write the Fast transpose Algorithm of the sparse matrix : Refer PPT
YIT, Moodbidri Page 6
BCS304- Data Structures and its Applications
Triple form of the sparse matrix is: Transpose of the Sparse matrix
Row Co Val Row Co Val
l l
A[0] 3 3 6 A[0] 3 3 6
A[1] 0 1 18 A[1] 0 1 5
A[2] 0 2 22 A[2] 0 1 9
A[3] 1 0 5 A[3] 1 0 18
A[4] 1 0 9 A[4] 1 1 1
A[5] 1 1 1 A[5] 2 0 22
A[6] 1 2 6 A[6] 2 1 6
-----------------------------------------------------------------------------------------------------------------------------
7. Define stack give the implementation of push(),pop() and display() function considering its full
and empty conditions?
Answer:
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning the
last element added to the stack is the first one to be removed. The operations that can be
performed on stack are:
Insert: Add element to the top of stack ( also called push Operation)
Delete: Remove the top element from the stack ( also called pop Operation)
Display: Print the elements of the stack
Underflow:occurs when an attempt is made to remove an element from an empty stack. when
the stack is empty, there are no elements to pop.
Overflow: occurs when an attempt is made to insert an element into ay stack. when the stack is
full, there is no space to insert element into the stack.
Program: to implement pop(), push() and Display() function
#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum size of the stack
YIT, Moodbidri Page 7
BCS304- Data Structures and its Applications
// Global variables for the stack
int stack[MAX];
int top = -1; // Indicates the top of the stack
// Function to check if the stack is full
intisFull() {
return top == MAX - 1;
}
// Function to check if the stack is empty
intisEmpty() {
return top == -1;
}
// Function to push an element onto the stack
void push(int value) {
if (isFull()) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
stack[++top] = value; // Increment top and add value
printf("%d pushed to stack\n", value);
}
}
// Function to pop an element from the stack
int pop() {
if (isEmpty()) {
printf("Stack Underflow! Cannot pop from empty stack\n");
return -1; // Return -1 or some error value
} else {
return stack[top--]; // Return value and decrement top
}
}
// Function to display the elements of the stack
void display() {
if (isEmpty()) {
printf("Stack is empty\n");
} else {
printf("Stack elements are:\n");
YIT, Moodbidri Page 8
BCS304- Data Structures and its Applications
for (int i = 0; i <= top; i++) {
printf("%d\n", stack[i]);
}
}
}
voidmain() {
// Example usage
push(10);
push(20);
push(30);
display();
printf("Popped element: %d\n", pop());
display();
}
-------------------------------------------------------------------------------------------------------------------------------
8. Write a program in C to implement push, pop and display operations for stacks using arrays.
Answer:
Refer Question 7
------------------------------------------------------------------------------------------------------------------------------
9. Write a function to evaluate the postfix expression. Illustrate the same for the given postfix
expression: ABC-D*+E$F+ and assume A=6, B=3, C=2, D=5, E=1 and F=7
Answer:To evaluate a postfix expression (also known as Reverse Polish Notation), we can use a
stack. The general approach is to read the expression from left to right and apply the following
rules:
1. If the character is an operand (like a variable or number), push it onto the stack.
2. If the character is an operator, pop the required numbers of operands from the stack,
apply the operator, and push the result back onto the stack.
SI Scanned Valu Op1 Op2 Result Stack
NO. Symbol e
1 A 6 6
2 B 3 6,3
3 C 2 6,3,2
YIT, Moodbidri Page 9
BCS304- Data Structures and its Applications
4 - 3 2 1 6,1
5 D 5 6,1,5
6 * 6,5
7 + 11
8 E 1 11,1
9 $ 11
10 F 7 11,7
11 + 18
The final result of the postfix expression ABC-D*+E$F+ is 18.
-------------------------------------------------------------------------------------------------------------------------------
10. Write functions in C for the following operations without using built-in functions
i) Compare two strings. ii) Concatenate two strings. iii) Reverse a string
Answer:
Function to compare two strings Function to Concatenate two strings
intcompareStrings() void concatenateStrings()
{ {
int i = 0; int i = 0, j = 0;
while (str1[i] != '\0'&& str2[i] != '\0') while (str1[i] != '\0')
{ {
if (str1[i] != str2[i]) result[j++] = str1[i++];
{ }
return str1[i] - str2[i];
} while (str2[i] != '\0')
i++; {
} result[j++] = str2[i++];
return str1[i] - str2[i]; }
} result[j] = '\0';
}
Function to reverse a String
void reverseString()
{
int start = 0; int end = 0;
while (str[end] != '\0')
{
end++;
}
YIT, Moodbidri Page 10
BCS304- Data Structures and its Applications
end--;
while (start < end)
{
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
-----------------------------------------------------------------------------------------------------------------------------
11. Write an algorithm to evaluate the postfix expression and apply the same for the postfix
expression
6,2,/,3,-,4,2,*,+
Answer:
To evaluate a postfix expression (also known as Reverse Polish Notation), we can use a stack.
The general approach is to read the expression from left to right and apply the following rules:
1. If the character is an operand (like a variable or number), push it onto the stack.
2. If the character is an operator, pop the required numbers of operands from the stack,
apply the operator, and push the result back onto the stack.
SI NO. Scanned Symbol Op1 Op2 Result Stack
1 6 6
2 2 6, 2
3 / 6 2 3 3
4 3 3,3
5 - 3 3 0
6 4 0,4
7 2 0,4,2
8 * 4 2 0,8
9 + 0 8 8
The result of the postfix expression 6, 2, /,3,-,4,2,*,+ is 8
----------------------------------------------------------------------------------------------------------------------------
12. Write the post fix form for the following using stack
YIT, Moodbidri Page 11
BCS304- Data Structures and its Applications
i. A*(B*C+D*E)+F ii. (a+(b*c)/(d-e))
I.
SNO Scanned Symbol Stack Postfix Expression
.
1 A - A
2 * * A
3 ( *( A
4 B *( AB
5 * *(* AB
6 C *(* ABC
7 + *(+ ABC*
8 D *(+ ABC*D
9 * *(+* ABC*D
10 E *(+* ABC*DE
11 ) * ABC*DE*+
12 + + ABC*DE*+*
13 F + ABC*DE*+*F
14 - ABC*DE*+*F+
ABC*CE*+*F+ is the postfix form of A*(B*C+D*E)+F
II.
SNO Scanned Symbol Stack Postfix Expression
.
1 ( ( -
2 a ( a
3 + (+ a
4 ( (+( a
5 b (+( ab
6 * (+(* ab
YIT, Moodbidri Page 12
BCS304- Data Structures and its Applications
7 c (+(* abc
8 ) (+ abc*
9 / (+/ abc*
10 ( (+/( abc*
11 d (+/( abc*d
12 - (+/(- abc*d
13 e (+/(- abc*de
14 ) (+/ abc*de-
15 ) - abc*de-/+
abc*de-/+ is the postfix form of (a+(b*c)/(d-e))
---------------------------------------------------------------------------------------------------------------------------
13. Convert the infix to prefix (A+B) * C –D + F
Answer:
Convert the infix to prefix (A+B) * C –D + F
Reverse the infix expression we get F+D – C*(B+A)
Obtain the postfix expression
Scanned Stack Expression
Symbol
F F
+ + F
D + FD
- +- FD
C +- FDC
* +-* FDC
( +- *( FDC
B +-*( FDCB
+ +-*(+ FDCB
A +-*(+ FDCBA
YIT, Moodbidri Page 13
BCS304- Data Structures and its Applications
) +- * FDCBA+
FDCBA+*-+
Reverse the Expression to obtain Prefix: +-*+ABCDF
14. Evaluate the prefix Expression: +, - , * , 2, 2, /, 16, 8, 5
Answer: Reverse the given expression 5, 8, 16, / ,2 , 2 ,*, -, +
Symbol OP1 OP2 Stack
5 5
8 5,8
16 5,8,16
/ 16 6 5,2
2 5,2,2
2 5,2,2,2
* 2 2 5,2,4
- 4 2 5,2
+ 2 5 7
NOTE:Try to solve previous year Question Papers
YIT, Moodbidri Page 14
BCS304- Data Structures and its Applications
YIT, Moodbidri Page 15