0% found this document useful (0 votes)
25 views

DSA - MODEL Question Paper Solutions

The document provides a comprehensive overview of data structures, including definitions, classifications, and examples of both primitive and non-primitive structures. It also covers algorithms for pattern matching, dynamic memory allocation functions in C, and implementations for stack and queue operations using arrays and linked lists. Additionally, it includes functions for string manipulation and polynomial addition using linked lists.

Uploaded by

dashidarud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

DSA - MODEL Question Paper Solutions

The document provides a comprehensive overview of data structures, including definitions, classifications, and examples of both primitive and non-primitive structures. It also covers algorithms for pattern matching, dynamic memory allocation functions in C, and implementations for stack and queue operations using arrays and linked lists. Additionally, it includes functions for string manipulation and polynomial addition using linked lists.

Uploaded by

dashidarud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Q.1 a) Define data structures.

With a neat diagram, explain the classification of data


structures with examples.
Ans Data Structure can be defined as the group of data elements which provides an
: efficient way of storing and organizing data in the computer so that it can be used
efficiently. Some examples of Data Structures are arrays, Linked List, Stack, Queue,
etc. Data Structures are widely used in almost every aspect of Computer Science i.e.
operating System, Compiler Design, Artificial intelligence, Graphics and many more.
CLASSIFICATION OF DATA STRUCTURES
Data structures are generally classified into
• Primitive data Structures
• Non-primitive data Structures

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.

Based on the structure and arrangement of data, non-primitive data structures is


further classified into

. Linear Data Structure


2. Non-linear Data Structure
1. Linear Data Structure: A data structure is said to be linear if its elements form a
sequence or a linear list. There are basically two ways of representing such linear
structure in memory.
 One way is to have the linear relationships between the elements represented
by means of sequential memory location. These linear structures are called
arrays.
 The other way is to have the linear relationship between the elements
represented by means of pointers or links. These linear structures are called
linked lists.
The common examples of linear data structure are Arrays, Queues, Stacks, Linked lists

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]);
}
}
}

Q.0 Explain in brief the different functions of dynamic memory allocation.


2 a)
Ans There are 4 library functions for dynamic memory allocation:

malloc()
calloc()
free()
realloc()

These library functions are defined under "stdlib.h"


malloc():

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().

The syntax is shown below:


ptr=(data_type*)realloc(ptr,newsize);

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);

This statement causes the space in memory pointed by ptr to be deallocated.


char *str;
str=(char*)malloc(10*sizeof(char));
free(str);
str=NULL;

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.

void my_strcat(char s1[],char s2[]){


int i=0,j=0;
while(s1[i]!='\0')i++;
while(s2[j]!='\0'){
s1[i++]=s2[j++];

}
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]);
}
}

b Write a program in C to implement a stack of integers using a singly linked list.


Ans #include<stdio.h>
#include<stdlib.h>
struct node {
int num;
struct node * link;
};
typedef struct node * NODE;NODE start = NULL;
NODE create() {
NODE snode;
snode = (NODE) malloc(sizeof(struct node));
if (snode == NULL) {
printf("\nMemory is not available");
exit(1);
}
printf("\nEnter the usn,Name,Branch, sem,PhoneNo of
the student:");
scanf("%d", snode -> num);
snode -> link = NULL;
return snode;
}

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;
}
}

ii. c function to concatenate two singly linked lists


listPointer concatenate(listPointer ptr1, listPointer ptr
2){

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;
};

void insertStart (struct Node **head, int data)


{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
newNode->data = data;
newNode->next = *head;
newNode->prev = NULL;
if (*head != NULL)
(*head)->prev = newNode;
*head = newNode;
}
Deleting a node at the end of the Doubly linked list
void last_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW\n");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nNode Deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nNode Deleted\n");
}
}

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.

Figure: Binary Tree

BINARY TREE REPRESENTATION


The storage representation of binary trees can be classified as
1. Array
representatio
n
2. Linked
representatio
n.

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.

These problems can be easily overcome by linked representation


Each node has three fields,
 LeftChild - which contains the address of left subtree
 RightChild - which contains the address of right subtree.
 Data - which contains the actual information

C Code for node:


typedef struct node
*treepointer;
typedef struct {
int data;
treepointer leftChild, rightChild;
}node;

Figure: Node representation


Linked representation of the binary tree

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.

We can represent a threaded binary tree in three ways.


1. One way Inorder Threading
2. Two way Inorder Threading
3. Two way Inorder Threading with header node

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy