DSA - MODEL Question Paper Solutions
DSA - MODEL Question Paper Solutions
1. Primitive data Structures: Primitive data structures are the fundamental data
types which are supported by a programming language. Basic data types such as
integer, real, character and Boolean are known as Primitive data Structures. These
data types consists of characters that cannot be divided and hence they also called
simple data types.
2. Non- Primitive data Structures: Non-primitive data structures are those data
structures which are created using primitive data structures. Examples of non-
primitive data structures is the processing of complex numbers, linked lists, stacks,
trees, and graphs.
2. Non-linear Data Structure: A data structure is said to be non-linear if the data are
not arranged in sequence or a linear. The insertion and deletion of data is not possible
in linear fashion. This structure is mainly used to represent data containing a
hierarchical relationship between elements. Trees and graphs are the examples of non-
linear data structure
What do you mean by pattern matching? Outline the Knuth Morris Pratt (KMP)
b) algorithm and illustrate it to find the occurrences of the following pattern.
P: ABCDABD
S: ABC ABCDAB ABCDABCDABDE
Ans Pattern matching: Pattern matching is the problem of deciding whether or not a given
string pattern P appears in a string text T. The length of P does not exceed the length
of T.
c) Write a program in C to implement push, pop and display operations for stacks using
arrays.
Ans /* Write a C program to implement STACK Operations */
: #include <stdio.h>
#include <stdlib.h>
int stack[6];
int top=-1,k=0;
int size;
void push();
void pop();
void display();
void main() {
int choice,f;
printf("Enter the size for stack\n");
scanf("%d",&size);
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
while(1) {
printf("Enter the choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("Wrong choice...\n");
}
}
}
void push() {
int num;
if(top==(size-1)){
printf("Stack Overflow\n");
} else {
printf("Enter the number to be pushed\n");
scanf("%d",&num);
top++;
stack[top]=num;
}
}
void pop() {
int num;
if(top==-1) {
printf("Stack Underflow\n");
} else {
num=stack[top];
printf("Popped element is %d\n",num);
top--;
}
}
void display()
{
int i;
if(top==-1) {
printf("Stack Underflow\n");
} else {
printf("Stack Contents....\n");
for(i=top;i>=0;i--) {
printf("%d\n",stack[i]);
}
}
}
malloc()
calloc()
free()
realloc()
The name malloc stands for "memory allocation".This function is used to allocate the
requirement memory-space during execution-time. The syntax is shown below:
data_type *p;
p=(data_type*)malloc(size);
here p is pointer variable data_type can be int, float or char size is number of bytes to
be allocated
If memory is successfully allocated, then address of the first byte of allocated space is
returned. If memory allocation fails, then NULL is returned.
For ex:
ptr=(int*)malloc(100*sizeof(int));
The above statement will allocate 200 bytes assuming sizeof(int)=2 bytes.
calloc():
The name calloc stands for "contiguous allocation". This function is used to allocate
the blocks of memory required during execution-time and at the same time,
automatically initialize memory with 0's. The syntax is shown below:
data_type *p;
p=(data_type*)calloc(n,size);
If memory is successfully allocated, then address of the first byte of allocate space is
returned. If memory allocation fails, then NULL is returned.
The allocated memory is initialized automatically to 0's.
realloc():
If the previously allocated memory is insufficient or more than sufficient. Then, you
can change memory-size previously allocated using realloc().
free():Dynamically allocated memory with either calloc() or malloc() does not get
return on its own. The programmer must use free() explicitly to release space.
The syntax is shown below: free(ptr);
Write functions in C for the following operations without using built-in functions i)
b) Compare two strings. ii) Concatenate two strings. iii) Reverse a string
1) strcmp(deststr, srcstr):String Comparison:- This function is used to
Ans compare two strings. The comparision starts with the first character of each
: string. The comparison continues till the corresponding characters differ or until
the end of the character is reached. The following values are returned after
comparison.
If the two strings are equal ,the function returns 0.
If s1 is greater than s2 a positive value is returned.
If s1 kis less than s2 negative value is returned.
int my_strcmp(char s1[],char s2[]){
int i;
i=0;
while(s1[i]==s2[i]){
if(s1[i]=='\0')break;
i++;
}
return s1[i]-s2[i];
}
2. Concatenate two strings: This function copies all characters of source string srcstr
to the end of the destination string deststr.The destination string should be greater in
size. The usage of this function is as follows.
}
s1[i++]='\0';
}
3. Reverse a string: This function is used to reverse all the characters in the string
srcstr except terminating null character.
void my_strrev(char s1[],char s2[]){
int i,len;
len=strlen(s1);
for(i=0;i<len;i++){
s2[len-1-i]=s1[i];
}
s2[i]='\0';
}
c) 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
Ans
Evaluation:
Q Develop a C program to implement insertion, deletion and display operations on Linear
3.a queue.
Ans #include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
int Q[MAXSIZE],front=-1,rear=-1;
void qinsert(int x)
{
if(rear==MAXSIZE-1)
printf("\n Queue is Full.");
else if(front==-1)
{
front=0;
rear=0;
Q[front]=x;
}
else
{
rear++;
Q[rear]=x;
}
}
void qdelete()
{
if(front==-1)
printf("\n Queue is Empty.");
else if(front==rear)
{
printf("\n %d is removed from Queue.",Q[front]);
front=-1;
rear=-1;
}
else
{
printf("\n %d is deleted from Queue.",Q[front]);
front++;
}
}
void display()
{
int i;
printf("\n The Queue elements are...\n");
if(front==-1)
printf("\n No elements in Queue.");
else
{
for(i=front;i<=rear;i++)
printf(" %d ",Q[i]);
}
}
NODE deletefront() {
NODE temp;
if (start == NULL) {
printf("\nLinked list is empty");
return NULL;
}if (start -> link == NULL) {
printf("\nThe Student node with usn:%d is deleted ",
start -> num);
count--;
free(start);
return NULL;
}
temp = start;
start = start -> link;
printf("\nThe Student node with usn:%d is deleted",
temp -> num);
count--;
free(temp);
return start;
}
NODE insertfront() {
NODE temp;
temp = create();
if (start == NULL) {
return temp;
}temp -> link = start;
return temp;
}
void display() {
NODE cur;
int num = 1;
if (start == NULL) {
printf("\nNo Contents to display in SLL \n");
return;
}
printf("\nThe contents of SLL: \n");
cur = start;
while (cur != NULL) {
printf("\n||%d|||", num);
cur = cur -> link;
}
}
void stackdemo() {
int ch;
while (1) {
printf("\n~~~Stack Demo using SLL~~~\n");
printf("\n1:Push operation \n2: Pop operation
\n3: Display \n4:Exit \n");
printf("\nEnter your choice for stack demo:");
scanf("%d", & ch);
switch (ch) {
case 1:
start = insertfront();
break;
case 2:
start = deletefront();
break;
case 3:
display();
break;
default:
return;
}
}
return;
}
Q 4 Write a C program to implement insertion, deletion and display operations on a
a circular queue
Ans #include<stdio.h>
#include<stdlib.h>
#include <stdio.h>
#include<stdlib.h>
#include<stdio_ext.h>
#define MAX 5
char cq[MAX];
int front = -1, rear = -1;
void insert(char);
void delete();
void display();
void main() {
int ch;
char item;
while (1) {
printf("\n\n~~Main Menu~~");
printf("\n==> 1. Insertion and Overflow Demo");
printf("\n==> 2. Deletion and Underflow Demo");
printf("\n==> 3. Display");
printf("\n==> 4. Exit");
printf("\nEnter Your Choice: ");
scanf("%d", & ch);
__fpurge(stdin);
switch (ch) {
case 1:
printf("\n\nEnter the element to be inserted: ");
scanf("%c", & item);
insert(item);
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nPlease enter a valid choice");
}
}
}
void insert(char item) {
if (front == (rear + 1) % MAX) {
printf("\n\n~~Circular Queue Overflow~~");
} else {
if (front == -1)
front = rear = 0;
else
rear = (rear + 1) % MAX;
cq[rear] = item;
}
}
void delete() {
char item;
if (front == -1) {
printf("\n\n~~Circular Queue Underflow~~");
} else {
item = cq[front];
printf("\n\nDeleted element from the queue is: %c ",
item);
if (front == rear) //only one element
front = rear = -1;
else
front = (front + 1) % MAX;
}
}
void display() {
int i;
if (front == -1) {
printf("\n\nCircular Queue Empty");
} else {
printf("\nCircular Queue contents are:\n");
printf("Front[%d]-> ", front);
for (i = front; i != rear; i = (i + 1) % MAX) {
printf(" %c", cq[i]);
}
printf(" %c", cq[i]);
printf(" <-[%d]Rear", rear);
}
}
b Write the C function to add two polynomials. Show the linked representation of the
below two polynomials and their addition using a circular singly linked list
P1: 5x3 + 4x2 +7x + 3
P2: 6x2 + 5 Output: add the above two polynomials and represent them using the
linked list.
polyPointer padd( polyPointer a, ployPointer b){
polyPointer c,rear,temp;
int sum;
MALLOC(rear,sizeof(*rear));
c=rear;
while( a && b){
switch(COMPARE(a →expon, b→expon){
case -1: //a →expon < b→expon
attach(b →coef , b→expon,&rear);
b = b→link;
break;
case 0: //a →expon = = b→expon
sum= a →coef + b →coef;
if(sum)
attach(sum, a→expon,&rear);
a = a → link;
b = b → link;
break;
case 1: //a →expon > b→expon
attach(a →coef, a→expon,&rear);
a = a → link;
}
}
/* copy rest of list a and then list b */
for(; a ; = a → link)
attach(a →coef, a→expon,&rear);
for(; b ; = b → link)
attach(b →coef, b→expon,&rear);
rear → link = NULL;
temp=c;
c=c → link;
free(temp);
return c;
}
void attach(float coefficient,int exponent,polyPointer *ptr){
polyPointer temp;
MALLOC(temp,sizeof(*temp));
temp → coeff=coefficient;
temp → expon=exponent;
(*ptr) → link=temp;
*ptr=temp;
}
Q 5 Write recursive C functions for inorder, preorder and postorder traversals of a binary
a tree. Also, find all the traversals for the given tree.
Ans void inorder(treepointer ptr)
{
if (ptr)
{
inorder (ptr→leftchild);
printf (“%d”,ptr→data);
inorder(ptr→rightchild);
}
}
void preorder (treepointer ptr)
{
if (ptr)
{
printf (“%d”,ptr→data) ;
preorder (ptr→leftchild);
preorder (ptr→rightchild);
}
}
void postorder(treepointer ptr)
{
if (ptr)
{
postorder(ptr→leftchild);
postorder(ptr→rightchild);
printf (“%d”,ptr→data);
}
}
b Write C functions for the following i) Search an element in the singly linked list. ii)
Concatenation of two singly linked list
Ans i. C function for Search an element in the singly linked list
int searchNode(struct node *head, int key)
{
struct node *temp = head;
while(temp != NULL)
{
if(temp->data == key)
return 1;
temp = temp->next;
}
}
listPointer temp;
if(!ptr1) return ptr2;
if(!ptr2) return ptr1;
for( temp=ptr1;temp->link;temp=temp->link);
temp->link=ptr2;
}
c Define Sparse matrix. For the given sparse matrix, give the linked list representation:
Ans A matrix which contains many zero entries or very few non-zero entries is called as
Sparse matrix. In the figure Below shown contains only 6 of 20 elements are nonzero
and that is sparse.
Q 6 Write C Functions for the following
a i) Inserting a node at the beginning of a Doubly linked list
ii) Deleting a node at the end of the Doubly linked list
Ans Inserting a node at the beginning of a Doubly linked list
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
b Define Binary tree. Explain the representation of a binary tree with a suitable
example.
Ans Definition: A binary tree T is defined as a finite set of nodes such that,
• T is empty or
• T consists of a root and two disjoint binary trees called the left subtree and the
right subtree.
Array representation:
A tree can be represented using an array, which is called sequential representation.
The nodes are numbered from 1 to n, and one dimensional array can be used to store
the nodes.
Position 0 of this array is left empty and the node numbered i is mapped to position i
of the array.
Below figure shows the array representation for both the trees of figure (a).
• For complete binary tree the array representation is ideal, as no space is wasted.
• For the skewed tree less than half the array is utilized.
Linked representation:
The problems in array representation are:
It is good for complete binary trees, but more memory is wasted for skewed and
many other binary trees.
The insertion and deletion of nodes from the middle of a tree require the movement
of many nodes to reflect the change in level number of these nodes.
c Define the Threaded binary tree. Construct Threaded binary for the following
elements: A, B, C, D, E, F, G, H, I
Ans The limitations of binary tree are:
1. In binary tree, there are n+1 null links out of 2n total links.
2. Traversing a tree with binary tree is time consuming. These limitations can be
overcome by threaded binary tree.
In the linked representation of any binary tree, there are more null links than actual
pointers. These null links are replaced by the pointers, called threads, which points to
other nodes in the tree.