0% found this document useful (0 votes)
77 views41 pages

DSC Answer Bank

The document provides information on abstract data types (ADT), linear and non-linear data structures, functions in C programming, the structure of a C program, decision control structures, and strings and string operations in C. It defines ADT as a type of data whose behavior is defined by a set of values and operations, with examples including stack, queue, and list. Linear data structures arrange elements sequentially, while non-linear structures do not have a single sequential arrangement. Functions are described as the basic building blocks of C programs that provide reusability and modularity. The structure of a C program is outlined as consisting of preprocessor commands, functions, variables, statements, expressions, and comments. Decision control structures and examples of

Uploaded by

Anshu Maurya
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)
77 views41 pages

DSC Answer Bank

The document provides information on abstract data types (ADT), linear and non-linear data structures, functions in C programming, the structure of a C program, decision control structures, and strings and string operations in C. It defines ADT as a type of data whose behavior is defined by a set of values and operations, with examples including stack, queue, and list. Linear data structures arrange elements sequentially, while non-linear structures do not have a single sequential arrangement. Functions are described as the basic building blocks of C programs that provide reusability and modularity. The structure of a C program is outlined as consisting of preprocessor commands, functions, variables, statements, expressions, and comments. Decision control structures and examples of

Uploaded by

Anshu Maurya
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/ 41

Module 1

1. Explain ADT with an example. Explain the Concept of Linear and Non-Linear Data Structures.

Ans) Abstract Data Type in Data Structures


● The Data Type is basically a type of data that can be used in different computer program. It
signifies the type like integer, float etc, the space like integer will take 4-bytes, character will take
1-byte of space etc.
● The abstract datatype is special kind of datatype, whose behavior is defined by a set of values and
set of operations. The keyword “Abstract” is used as we can use these datatypes, we can perform
different operations. But how those operations are working that is totally hidden from the user.
The ADT is made of with primitive datatypes, but operation logics are hidden.
● Some examples of ADT are Stack, Queue, List etc.

What is a Linear Data Structure?


● It is a type of Data Structure where the data elements get linearly or sequentially arranged. The
elements attach themselves to their next and previous adjacents. The structure involves only a
single level- allowing a user to traverse all its components in a single run.
● The linear data structure is very easy to understand and implement due to its linear arrangement,
for example, stack, array, linked list, queue, etc.

What Is a Non-Linear Data Structure?


● It is a form of data structure where the data elements don’t stay arranged linearly or sequentially.
Since the data structure is non-linear, it does not involve a single level. Therefore, a user can’t
traverse all of its elements in a single run.
● The non-linear data structure is not very easy to implement as compared to the linear data
structure. The utilization of computer memory is more efficient in this case, for example, graphs
and trees.

2. Define Function. Describe the types of Functions with suitable ‘C’ Programs and Output.

Ans) Function
In c, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the C program.

Types of Functions
There are two types of functions in C programming:

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.

User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.
3. Draw the structure of ‘C’ Program and discuss the same with simple ‘C’ Program.

Ans) A ‘C’ program basically consists of the following parts:

● Preprocessor Commands
● Functions
● Variables
● Statements & Expressions
● Comments

#include <stdio.h>
int main(){
/* my first program in C */
printf("Hello, World!");
return 0;
}

4. Explain about Decision Control Structures in ‘C’ Language with suitable


examples and necessary diagrams.

Ans)

5. Define String. Show any five String operations with suitable ‘C’ Code.

Ans)
String in C programming is a sequence of characters terminated with a null character ‘\0’.
Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a unique character ‘\0’.

1) puts() and gets()


The two popular functions of string header file gets and puts are used to take the input from the user and
display the string respectively.To understand briefly the working of the string handling functions in c of
puts and gets, the gets() function, allows the ensure to enter characters followed by enter key. And it also
enables the user to add spaced separated strings. Whereas, the puts() function is also one of the types of
strings in C, is used for writing a line for the output screen. It is similar to the printf() function

Both of these functions are defined in string.h file. Let’s see one example of these functions:

#include main()
Int main()
{
char temp[20];
printf(“Enter your Name”);
gets(temp);
printf(“My Name is: ”);
puts(temp);
return 0;
}

2) strcat()
For the cases when one string has to be appended at the end of another string, this function is being used.
Function strcat can append a copy of the source string at the end of the destination string. The strcat() is
one of the string operations in c which concatenates two strings, meaning it joins the character strings
end-to-end. In the strcat() operation, the destination string’s null character will be overwritten by the
source string’s first character, and the previous null character would now be added at the end of the new
destination string which is a result of stcrat() operation.

The user has to pass two arguments that are described below:
● src
● dest

Here at the place of “src” string is specified, while at the place of ‘dest’ the destination string in which we
have to append the source string is specified.

Example:
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}

Output: after before

3) Function strlen()
One more function of string header file that can be directly used for the strings is strlen(). You can use the
function strlen(), the string function in C, when you have to find out the length of any string. The strlen()
string functions in c basically calculate the length of a given string. However, one can also write a
program manually to find out the length of any string, but the use of this direct function can save your
time and the example is given below:
#include<stdio.h>
int main()
{
int length;
char s[20] = “We are Here”;
length=strlen(s);
printf(“\Length of the string is = %d \n”, length);
return 0;
}

Output: Length of the string is = 11

4) Function strcpy()
If you have to copy the content of one string to another string, then this function is being used. Even the
null characters are copied in the process. Syntax of the function is strcpy(dest,source). The function can
copy the content of one string to another. One example of the function is given below:

#include<string.h>
int main()
{
char src[20]= “ Destination”;
char dest[20]= “”;
printf(“\n source string is = %s”, src);
printf(“\n destination string is = %s”, dest);
strcpy(dest, src);
printf (“\ntarget string after strcpy() = %s”, dest);
return 0;
}

Output:

Source string is = Destination


Target string is =
Target string after strcpy() = Destination

5) Function strcmp()
To compare two strings to know whether they are same or not we can use strcmp() function.This string
functions in c, compares two strings. While comparing the strings takes two parameters into account
namely –
str1
str2
On comparing the return value be determined basis the strings setup as shown below.

The function returns a definite value that may be either 0, >0, or <0. In this function, the two values
passed are treated as case sensitive means ‘A’ and ‘a’ are treated as different letters. The values returned
by the function are used as:

● 0 is returned when two strings are the same


● If str1<str2 then a negative value is returned
● If str1>str2 then a positive value is returned

Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;
char str2[]=”Trophy”;
int I,j,k;
i=strcmp(str1, “copy”);
j=strcmp(str1, str2);
k-strcmp(str1, “f”);
printf(“\n %d %d %d”,I,j,k);
return 0;
}

Output: 0 -1 1

Module 2
1. Write an algorithm to convert infix to postfix expression and explain the same for any given
expression.

Ans)
Algorithm:
Step1: Start the Program
Step2: Include the necessary header files
Step3: Declare the functions with the prototypes
Step4: Declare the Variables
Step 5: Get the valid infix expression using scanf() function
Step 6: Call the function evaluate() and start scanning the input tokens one by one.
Step 7: If the scanned token is an operator then perform the following operations:
● If the symbol is ‘(‘ then push it onto stack
● If the symbol is ‘)’ then pop the operators from ‘(‘ to ‘)’ and push it to postfix expression
● If the symbol is ‘+’ or ‘-‘ or ‘*’ or ’/’ or ‘%’ or ‘^’ or ‘$’ then check the precedence of the
operator with the operator in stack.
● If the stack operator is of higher precedence / equal precedence than the incoming operator, then
pop the stack operator to postfix expression and then the incoming operator to stack.
● Else push the operator onto stack.
Step 8: If the scanned token is an operand then push into postfix expression
Step 9: Continue the steps 7 & 8 until the input token becomes empty
Step 10: Print the Postfix expression
Step 11: Stop the Program execution

Example:

A*(B+C)*D
Symbol Stack Output

A empty A

* + A

( *( A

B *( AB

+ *(+ AB

C *(+ ABC

) * ABC+

* * ABC+*

D empty ABC+*D*

2. Write a Program in ‘C’ to implement stack data structure with its associated operations.

Ans) A menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)

a. Push an Element on to Stack


b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
int s[5],top=-1;

void push()
{
if(top==4)
printf("\nStack overflow!!!!");
else
{
printf("\nEnter element to insert:");
scanf("%d",&s[++top]);
}
}

void pop()
{
if(top==-1)
printf("\nStack underflow!!!");
else
printf("\nElement popped is: %d",s[top--]);
}

void disp()
{
int t=top;
if(t==-1)
printf("\nStack empty!!");
else
printf("\nStack elements are:\n");
while(t>=0)
printf("%d ",s[t--]);
}

void pali()
{
int num[5],rev[5],i,t;
for(i=0,t=top;t>=0;i++,t--)
num[i]=rev[t]=s[t];
for(i=0;i<=top;i++)
if(num[i]!=rev[i])
break;
if(i==top+1)
printf("\nIt is a palindrome");
else
printf("\nIt is not a palindrome");
}
int main()
{
int ch;
do
{
printf("\n...Stack operations.....\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.Palindrome\n");
printf("4.Display\n");
printf("5.Exit\n________________\n");
printf("Enter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();break;
case 2:pop();break;
case 3:pali();break;
case 4:disp();break;
case 5:exit(0);
default:printf("\nInvalid choice");
}
}
while(1);
return 0;
}

3. Define stack and show how stacks are represented? List down the applications
of stack.

Ans) A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc.

A real-world stack allows operations at one end only. For example, we can place or remove a card or plate
from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any
given time, we can only access the top element of a stack.

This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is
placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH
operation and removal operation is called POP operation.

Application of the Stack

● A Stack can be used for evaluating expressions consisting of operands and operators.
● Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
● It can also be used to convert one form of expression to another form.
● It can be used for systematic Memory Management.

4. Describe the types of expression and show how postfix expression evaluation is done with suitable
examples.

Ans) Types of Expressions in C

Arithmetic expressions
The arithmetic expression is evaluated in specific order considering the operator's precedence, and the
result of an expression will be based on the type of variable.
An arithmetic expression can be written in three different but equivalent notations, i.e., without changing
the essence or output of an expression. These notations are −
Infix Notation
We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is
easy for us humans to read, write, and speak in infix notation

Prefix Notation(polish notation)


In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish
Notation.

Postfix Notation(Reverse polish notation)


This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed
to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its
infix notation a + b.

Infix to Postfix A*(B+C)*D

Symbol Stack Output

A empty A

* + A

( *( A

B *( AB

+ *(+ AB

C *(+ ABC

) * ABC+

* * ABC+*

D empty ABC+*D*

Relational expressions
Relational operators >, <, ==,!= etc are used to compare 2 operands. Relational expressions consisting of
operands, variables, operators, and the result after evaluation would be either true or false.

Logical expressions
Relational expressions and arithmetic expressions are connected with the logical operators, and the result
after an evaluation is stored in the variable, which is either true or false.
Conditional expressions
The general syntax of conditional expression is:
Exp1? Exp2: Exp3
From the given above expressions, the first expression (exp1) is conditional, and if the condition is
satisfied, then expression2 will be executed; otherwise, expression3 will be performed.

5. Mention the need for Prefix and Postfix expressions.

Ans) Need of Prefix and Postfix Notations:


● Prefix notations are needed when we require operators before the operands while postfix
notations are needed when we require operators after the operands.
● Prefix notations are used in many programming languages like LISP.
● Prefix notations and Prefix notations can be evaluated faster than the infix notation.
● Postfix notations can be used in intermediate code generation in compiler design.
● Prefix and Postfix notations are easier to parse for a machine.
● With prefix and postfix notation there is never any question like operator precedence.
● There is no issue of left-right associativity.

Advantages of Postfix over Prefix Notations:

● Postfix notation has fewer overheads of parenthesis. i.e., it takes less time for parsing.
● Postfix expressions can be evaluated easily as compared to other notations.

Module 3
1. Define Queue ADT. Compare Queue with Stack data structure.

Ans) Queue is an abstract data structure, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out
methodology, i.e., the data item stored first will be accessed first.

examples can be seen as queues at the ticket windows and bus-stops.

What is a Stack Data Structure?


You can refer to Stack as a linear form of data structure. In this, a user can delete and insert elements from
only one side of a list. It is known as the top. The stack data structure implements and follows the Last In,
First Out (LIFO) principle. It implies that the element that is inserted last comes out first.

The process of inserting an element in the stack is known as the push operation. Here, the deletion of
elements is known as the pop operation. A user can feasibly keep track of the last function/element of the
list in a stack using a pointer (top).

What Is a Queue Data Structure?


You can also refer to Queue as a linear form of data structure. In this, a user can insert elements from only
one side of the list. It is known as the rear. Also, one can delete these elements from another side- known
as the front. This type of data structure implements and follows the First In, First Out (FIFO) principle. It
implies that the first element that inserts into a list will come out first.

The process of inserting an element into a queue is known as the enqueue operation. Here, the process of
deleting an element is known as the dequeue operation. A user can always hold two pointers in a queue.
The front pointer points to the first inserted element that is still in the list. The second pointer is the rear
one that points to the last inserted element in the list.

2. Write a Program in ‘C’ to implement Queue data structure with its associated operations.

Ans)
#include <stdio.h>
# define SIZE 100
void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch;
while (1)
{
printf("1.Enqueue Operation\n");
printf("2.Dequeue Operation\n");
printf("3.Display the Queue\n");
printf("4.Exit\n");
printf("Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3: show();
break;
case 4: exit(0);
default:
printf("Incorrect choice \n");
}
}
}

void enqueue()
{
int insert_item;
if (Rear == SIZE - 1)
printf("Overflow \n");
else
{
if (Front == - 1)

Front = 0;
printf("Element to be inserted in the Queue\n : ");
scanf("%d", &insert_item);
Rear = Rear + 1;
inp_arr[Rear] = insert_item;
}
}

void dequeue()
{
if (Front == - 1 || Front > Rear)
{
printf("Underflow \n");
return ;
}
else
{
printf("Element deleted from the Queue: %d\n", inp_arr[Front]);
Front = Front + 1;
}
}

void show()
{

if (Front == - 1)
printf("Empty Queue \n");
else
{
printf("Queue: \n");
for (int i = Front; i <= Rear; i++)
printf("%d ", inp_arr[i]);
printf("\n");
}
}

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 3
Queue:
10 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 2
Element deleted from the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations: 3
Queue:
20

3. Explain the Concept of Circular Queue with examples. Also list the advantages of the same.

Ans) A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out)
principle except that the last position is connected to the first position in a circular queue that forms a
circle. It is also known as a Ring Buffer.

There was one limitation in the array implementation of Queue


If the rear reaches to the end position of the Queue then there might be possibility that some vacant spaces
are left in the beginning which cannot be utilized. So, to overcome such limitations, the concept of the
circular queue was introduced.

As we can see in the above image, the rear is at the last position of the Queue and front is pointing
somewhere rather than the 0th position. In the above array, there are only two elements and other three
positions are empty. The rear is at the last position of the Queue; if we try to insert the element then it will
show that there are no empty spaces in the Queue. There is one solution to avoid such wastage of memory
space by shifting both the elements at the left and adjust the front and rear end accordingly. It is not a
practically good approach because shifting all the elements will consume lots of time. The efficient
approach to avoid the wastage of the memory is to use the circular queue data structure.

Advantages
Circular Queues offer a quick and clean way to store FIFO data with a maximum size.

● Doesn’t use dynamic memory → No memory leaks


● Conserves memory as we only store up to our capacity (opposed to a queue which could continue
to grow if input outpaces output.)
● Simple Implementation → easy to trust and test
● Never has to reorganize / copy data around
● All operations occur in constant time O(1)

4. Explain the concept of Priority Queue and show how it is implemented in ‘C’ code using Arrays.

Ans) A priority queue is a special type of queue in which each element is associated with a priority value.
And, elements are served on the basis of their priority. That is, higher priority elements are served first.
However, if elements with the same priority occur, they are served according to their order in
the queue.

Assigning Priority Value


Generally, the value of the element itself is considered for assigning the priority.
For example, The element with the highest value is considered the highest priority element. However, in
other cases, we can assume the element with the lowest value as the highest priority element.
We can also set priorities according to our needs.

Types of Priority Queue


There are two types of priority queues based on the priority of elements.
● If the element with the smallest value has the highest priority, then that priority queue is called the
min priority queue.
● If the element with a higher value has the highest priority, then that priority queue is known as the
max priority queue.

Removing the Highest Priority Element.

Some of the applications of a priority queue are:


● Dijkstra's algorithm
● for implementing stack
● for load balancing and interrupt handling in an operating system
● for data compression in Huffman code
Priority queue can be implemented using an array, a linked list, a heap data structure, or a
binary search tree. Among these data structures, heap data structure provides an efficient
implementation of priority queues.

Hence, we will be using the heap data structure to implement the priority queue in this tutorial.
A max-heap is implemented in the following operations.

1. Inserting an Element into the Priority Queue


Inserting an element into a priority queue (max-heap) is done by the following steps.
Insert the new element at the end of the tree.
Insert an element at the end of the queue.

Heapify the tree

Algorithm for insertion of an element into priority queue (max-heap)


If there is no node,
create a newNode.
else (a node is already present)
insert the newNode at the end (last node from left to right.)
heapify the array

2. Deleting an Element from the Priority Queue


Deleting an element from a priority queue (max-heap) is done as follows:
Select the element to be deleted.
Swap it with the last element.

Swap with the last leaf node element


Remove the last element.
Swap with the last leaf node element

Heapify the priority queue

Algorithm for deletion of an element in the priority queue (max-heap)


If nodeToBeDeleted is the leafNode
remove the node
Else swap nodeToBeDeleted with the lastLeafNode
remove noteToBeDeleted
heapify the array

3. Peeking from the Priority Queue (Find max/min)


Peek operation returns the maximum element from Max Heap or minimum element from Min Heap
without deleting the node.
For both Max heap and Min Heap
return rootNode

5. Explain about Deque and Multiple Queue.

Ans) Deque:
Deque or Double Ended Queue is a type of queue in which insertion and removal of elements can either
be performed from the front or the rear. Thus, it does not follow FIFO rule (First In First Out).

Types of Deque
Input Restricted Deque
In this deque, input is restricted at a single end but allows deletion at both the ends.

Output Restricted Deque


In this deque, output is restricted at a single end but allows insertion at both the ends.

Operations on a Deque
Before performing the following operations, these steps are followed.
Take an array (deque) of size n.
Set two pointers at the first position and set front = -1 and rear = 0.

Operations performed on deque


There are the following operations that can be applied on a deque -
● Insertion at front
● Insertion at rear
● Deletion at front
● Deletion at rear

Insertion at the front end


In this operation, the element is inserted from the front end of the queue. Before implementing the
operation, we first have to check whether the queue is full or not. If the queue is not full, then the element
can be inserted from the front end by using the below conditions:

If the queue is empty, both rear and front are initialized with 0. Now, both will point to the first element.
Otherwise, check the position of the front if the front is less than 1 (front < 1), then reinitialize it by front
= n - 1, i.e., the last index of the array.

Insertion at the rear end


In this operation, the element is inserted from the rear end of the queue. Before implementing
the operation, we first have to check again whether the queue is full or not. If the queue is not
full, then the element can be inserted from the rear end by using the below conditions:

If the queue is empty, both rear and front are initialized with 0. Now, both will point to the
first element.
Otherwise, increment the rear by 1. If the rear is at last index (or size - 1), then instead of
increasing it by 1, we have to make it equal to 0.

Deletion at the front end


In this operation, the element is deleted from the front end of the queue. Before implementing the
operation, we first have to check whether the queue is empty or not.
If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot perform the deletion. If
the queue is not full, then the element can be inserted from the front end by using the below conditions:
If the deque has only one element, set rear = -1 and front = -1.
Else if front is at end (that means front = size - 1), set front = 0.

Deletion at the rear end


In this operation, the element is deleted from the rear end of the queue. Before implementing the
operation, we first have to check whether the queue is empty or not.
If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot perform the deletion.
If the deque has only one element, set rear = -1 and front = -1.
If rear = 0 (rear is at front), then set rear = n - 1.
Else, decrement the rear by 1 (or, rear = rear -1).

Check empty
This operation is performed to check whether the deque is empty or not. If front = -1, it
means that the deque is empty.
Check full
This operation is performed to check whether the deque is full or not. If front = rear + 1, or
front = 0 and rear = n - 1 it means that the deque is full.

The time complexity of all of the above operations of the deque is O(1), i.e., constant.

Applications of deque
● Deque can be used as both stack and queue, as it supports both operations.
● Deque can be used as a palindrome checker means that if we read the string from both ends,
● the string would be the same.

Multiple Queue:
● Multi queue is a data structure in which multiple queues are maintained.
● This type of data structures are utilized for process scheduling.
● Use one dimensional array or multidimensional array to illustrate a multiple queue.

● A multi queue implementation by using a single dimensional array along ‘m’ elements is
illustrated in Figure. Each of queues contains ‘n’ elements that are mapped to a linear array of ‘m’
elements.
● Multiple Queue can be placed in single one dimensional array.
● Insertion is possible only one end (i,e) rear & deletion is possible at other end (i,e) front of each
desired queue. This makes effective utilization of available memory space.
● Initially divide memory space into ‘n’ parts according to sizes of these ‘n’ queues.

ADVANTAGES
● Multi-line queues elements are capable of switching from one queue to another.
● Multiple-line queues use memory space more efficiently.
● With multiple lines, even large crowds are more manageable and don’t hinder the foot traffic.

DISADVANTAGES
● Multiple Queues creates illusory correlation (i,e) When there are multiple queues running at the
same time, illusion often perceive the other queue to be moving faster than the residing queue.
● Multiple-line queues encourage line-switching. when a customer is in rush, he or she may decide
to ditch the queue they have been standing in and switch to another.
● Multiple Queues rarely results in faster checkout, but does lead to momentary chaos, confusion
and even altercations between customers.

APPLICATION
Centralized service dashboard
The ability to both serve visitors and access service metrics without switching to a different platform is a
huge time-saver, and one of the top features any queue management system needs.

SMS notifications
Integrating online queue systems with SMS messaging is more important in a short span of time.

Service data analysis


A customer queue system with data analytics gives the valuable insights into:
Customer behavior: It analyzes the customer in which service they seek out the most, how often they walk
away, how many no-shows you get, their history of service interactions, etc.
Service performance metrics: The metrics such as average wait time, servicing time, queue length etc.,are
considered to make your service better.
Employee performance: It services the most visitors, which employee needs to be rewarded for
overperforming or get additional training due to falling behind.
Unable to load…..
Error 404

restart your device


Module 4
1. Compare Sequential and Linked Organizations with any 10 points.

Ans) Comparison of Sequential and Linked Organization

ARRAY LINKED LIST

Basic It is a consistent set of a fixed It is an ordered set comprising a


number of data items. variable number of data items.

Size Specified during declaration. No need to specify; grow and shrink


during execution.

Storage Allocation Element location is allocated Element position is assigned during


during compile time. run time.

Order of the elements Stored consecutively Stored randomly

Accessing the element Direct or randomly accessed, i.e., Sequentially accessed, i.e., Traverse
Specify the array index or starting from the first node in the list
subscript. by the pointer.

Insertion and deletion of Slow relatively as shifting is Easier, fast and efficient.
element required.

Searching Binary search and linear search Linear search

Memory required Less More

Memory Utilization Ineffective Efficient

Pointers Not used Used

2. Draw the node structure of Singly Linked List. Write the Algorithm and ‘C’ Program to show how to
insert a node at the beginning, at End and at given Location.

Ans)
Insertion in Linked List At the front/beginning of the linked list
● The new node is always added before the head of the given Linked List.
● The newly added node becomes the new head of the Linked List.
● Call the function that adds at the front of the list is push().
● The push() must receive a pointer to the head pointer because the push must change the head
pointer to point to the new node.

// Given a reference (pointer to pointer) to the head of a list and an


int, inserts a new node on the front of the list.
void push(struct Node** head_ref, int new_data)
{
// 1. allocate node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// 2. put in the data
new_node->data = new_data;
// 3. Make next of new node as head
new_node->next = (*head_ref);
// 4. move the head to point to the new node
(*head_ref) = new_node;
}

Insertion in Linked List After a given node


● Firstly, check if the given previous node is NULL or not.
● Then, allocate a new node and
● Assign the data to the new node
● And then make the next of new node as the next of previous node.
● Finally, move the next of the previous node as a new node.

// Given a node prev_node, insert a new node after the given prev_node
void insertAfter(Node* prev_node, int new_data)
{
// 1. Check if the given prev_node is NULL
if (prev_node == NULL)
{
cout << "The given previous node cannot be NULL";
return;
}
// 2. Allocate new node
Node* new_node = new Node();
// 3. Put in the data
new_node->data = new_data;
// 4. Make next of new node as next of prev_node
new_node->next = prev_node->next;
// 5. move the next of prev_node as new_node
prev_node->next = new_node;
}

Insertion in Linked List At the end of the linked list


● The new node is always added after the last node of the given Linked List.
● Since a Linked List is typically represented by the head of it, we have to traverse the list till the
end and then change the next to last node to a new node.

// Given a reference (pointer to pointer) to the head of a list and an


int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
// 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
struct Node *last = *head_ref; // used in step 5
// 2. put in the data
new_node->data = new_data;
// 3. This new node is going to be the last node, so make next of it as
NULL.
new_node->next = NULL;
// 4. If the Linked List is empty, then make the new node as head
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
// 5. Else traverse till the last node
while (last->next != NULL)
last = last->next;
// 6. Change the next of last node
last->next = new_node;
return;
}

3. Draw the node structure of Doubly Linked List. Write the Algorithm and ‘C’ Program to show its
deletion and traversal operations.

Ans)

Deletion in Linked List


Deletion from Beginning
//Point head to the next node i.e. second node
temp = head head = head->next
//Make sure to free unused memory
free(temp);

Delete from End


//Point head to the previous element i.e. last second
//element Change next pointer to null
struct node *end = head;
struct node *prev = NULL;
while(end->next)
{
prev = end;
end = end->next;
}
prev->next = NULL;
//Make sure to free unused memory
free(end);

Delete from Middle:


//Keeps track of pointer before node to
//delete and pointer to node to delete
temp = head;
prev = head;
for(int i = 0; i < position; i++)
{
if(i == 0 && position == 1)
head = head->next;
free(temp)
else
{
if (i == position - 1 && temp)
{
prev->next = temp->next;
free(temp);
}
else
{
prev = temp;
if(prev == NULL)
// position was greater than number of nodes in the list break;
temp = temp->next;
} } }

Search in Linked List

● Initialize a node pointer, current = head.


● Do following while current is not NULL
1. If the current value (i.e., current->key) is equal to the key being searched return true.
2. Otherwise, move to the next node (current = current->next).
● If the key is not found, return false

// Iterative C program to search an element in the linked list


#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Link list node
struct Node {
int key;
struct Node* next;
};
// Given a reference (pointer to pointer) to the head of a list and an
int, push a new node on
the front of the list.
void push(struct Node** head_ref, int new_key)
{
// allocate node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// put in the key
new_node->key = new_key;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// Checks whether the value x is present in linked list
bool search(struct Node* head, int x)
{
struct Node* current = head; // Initialize current
while (current != NULL) {
if (current->key == x)
return true;
current = current->next;
}
return false;
}
int main()
{
// Start with the empty list
struct Node* head = NULL;
int x = 21;
// Use push() to construct below list 14->21->11->30->10
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
// Function call
search(head, 21) ? printf("Yes") : printf("No");
return 0;
}

4. Explain the operations of Circular Doubly Linked List.

Ans)

5. Show how polynomials are represented using Linked List. Implement the following operations
Addition and Multiplication for any given two polynomials.

Ans)
● A polynomial is a mathematical expression consisting of a sum of terms, each term including a
variable or variables raised to a power and multiplied by a coefficient. The simplest polynomials
have one variable.
● Representation of a Polynomial: A polynomial is an expression that contains more than two
terms. A term is made up of coefficient and exponent. An example of polynomial is
P(x) = 4x3+6x2+7x+9
● A polynomial thus may be represented using arrays or linked lists.
● Array representation assumes that the exponents of the given expression are arranged from 0 to
the highest value (degree), which is represented by the subscript of the array beginning with 0.
● The coefficients of the respective exponent are placed at an appropriate index in the array.

Module 5
1. Draw the Structure of Binary Tree and show how the types of traversals are done in the binary tree for
any given expression.

Ans) Binary Tree is defined as a tree data structure where each node has at most 2 children. Since each
element in a binary tree can have only 2 children, we typically name them the left and right child.

Binary Tree Representation

A Binary tree is represented by a pointer to the topmost node (commonly known as the “root”) of the tree.
If the tree is empty, then the value of the root is NULL. Each node of a Binary Tree contains the following
parts:
● Data
● Pointer to left child
● Pointer to right child

Basic Operation On Binary Tree:


● Inserting an element.
● Removing an element.
● Searching for an element.
● Traversing the tree.
Auxiliary Operation On Binary Tree:
● Finding the height of the tree
● Find the level of a node of the tree
● Finding the size of the entire tree.

Tree Traversals (Inorder, Preorder and Postorder)


Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to
traverse them, trees can be traversed in different ways. The following are the generally used methods for
traversing trees:

Inorder Traversal:
Algorithm Inorder(tree)
● Traverse the left subtree, i.e., call Inorder(left->subtree)
● Visit the root.
● Traverse the right subtree, i.e., call Inorder(right->subtree)
Uses of Inorder Traversal:
In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get
nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed
can be used.
Example: In order traversal for the above-given figure is 4 2 5 1 3.

Preorder Traversal:
Algorithm Preorder(tree)
● Visit the root.
● Traverse the left subtree, i.e., call Preorder(left->subtree)
● Traverse the right subtree, i.e., call Preorder(right->subtree)
Uses of Preorder:
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix
expressions on an expression tree.
Example: Preorder traversal for the above-given figure is 1 2 4 5 3.

Postorder Traversal:
Algorithm Postorder(tree)
● Traverse the left subtree, i.e., call Postorder(left->subtree)
● Traverse the right subtree, i.e., call Postorder(right->subtree)
● Visit the root
Uses of Postorder:
Postorder traversal is used to delete the tree. Please see the question for the deletion of a tree for details.
Postorder traversal is also useful to get the postfix expression of an expression tree
Example: Postorder traversal for the above-given figure is 4 5 2 3 1

2. Write a ‘C’ Program to implement Binary Tree Operations.

Ans)

#include<stdio.h>
#include<stdlib.h>
struct BST
{
int data;
struct BST *lchild;
struct BST *rchild;
};
typedef struct BST * NODE;

NODE create()
{
NODE temp;
temp = (NODE) malloc(sizeof(struct BST));
printf("\nEnter The value: ");
scanf("%d", &temp->data);

temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}

void insert(NODE root, NODE newnode);


void inorder(NODE root);
void preorder(NODE root);
void postorder(NODE root);
void search(NODE root);

void insert(NODE root, NODE newnode)


{
/*Note: if newnode->data == root->data it will be skipped. No duplicate
nodes are allowed */

if (newnode->data < root->data)


{
if (root->lchild == NULL)
root->lchild = newnode;
else
insert(root->lchild, newnode);
}
if (newnode->data > root->data)
{
if (root->rchild == NULL)
root->rchild = newnode;
else
insert(root->rchild, newnode);
}
}

void search(NODE root)


{
int key;
NODE cur;
if(root == NULL)
{
printf("\nBST is empty.");
return;
}
printf("\nEnter Element to be searched: ");
scanf("%d", &key);
cur = root;
while (cur != NULL)
{
if (cur->data == key)
{
printf("\nKey element is present in BST");
return;
}
if (key < cur->data)
cur = cur->lchild;
else
cur = cur->rchild;
}
printf("\nKey element is not found in the BST");
}

void inorder(NODE root)


{
if(root != NULL)
{
inorder(root->lchild);
printf("%d ", root->data);
inorder(root->rchild);
}
}

void preorder(NODE root)


{
if (root != NULL)
{
printf("%d ", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}

void postorder(NODE root)


{
if (root != NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("%d ", root->data);
}
}

void main()
{
int ch, key, val, i, n;
NODE root = NULL, newnode;
while(1)
{
printf("\n~~~~BST MENU~~~~");
printf("\n1.Create a BST");
printf("\n2.Search");
printf("\n3.BST Traversals: ");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:printf("\nEnter the number of elements: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
newnode = create();
if (root == NULL)
root = newnode;
else
insert(root, newnode);
}
break;
case 2:if (root == NULL)
printf("\nTree Is Not Created");
else
{
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
case 3:search(root);
break;

case 4:exit(0);
}
}
}
Output:
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:

4.Exit
Enter your choice: 1

Enter the number of elements: 12


Enter The value: 6
Enter The value: 9
Enter The value: 5
Enter The value: 2
Enter The value: 8
Enter The value: 15
Enter The value: 24
Enter The value: 14
Enter The value: 7
Enter The value: 8
Enter The value: 5
Enter The value: 2

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 3

The Preorder display: 6 5 2 9 8 7 15 14 24


The Inorder display: 2 5 6 7 8 9 14 15 24
The Postorder display: 2 5 7 8 14 24 15 9 6

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2

Enter Element to be searched: 66


Key element is not found in the BST

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2

Enter Element to be searched: 14


Key element is present in BST

~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 4

3. Explain the concept of Threaded Binary Trees and also List down the applications of Trees.

Ans) In the linked representation of binary trees, more than one half of the link fields contain NULL
values which results in wastage of storage space. If a binary tree consists of n nodes then n+1 link fields
contain NULL values. So in order to effectively manage the space, a method was devised by Perlis and
Thornton in which the NULL links are replaced with special links known as threads. Such binary trees
with threads are known as threaded binary trees. Each node in a threaded binary tree either contains a link
to its child node or thread to other nodes in the tree.
Types of Threaded Binary Tree
There are two types of threaded Binary Tree:
● One-way threaded Binary Tree
● Two- way threaded Binary Tree

Applications of trees
The following are the applications of trees:

Storing naturally hierarchical data: Trees are used to store the data in the hierarchical structure. For
example, the file system. The file system stored on the disc drive, the file and folder are in the form of
the naturally hierarchical data and stored in the form of trees.

Organize data: It is used to organize data for efficient insertion, deletion and searching. For example, a
binary tree has a logN time for searching an element.

Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and efficient way for
dynamic spell checking.

Heap: It is also a tree data structure implemented using arrays. It is used to implement priority queues.

B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to implement indexing in
databases.

Routing table: The tree data structure is also used to store the data in routing tables in the routers.

4. Define Graph. How the graphs are represented? Explain the same with suitable Example.

Ans) A graph data structure is a collection of nodes that have data and are connected to other nodes. For
example. On facebook, everything is a node. That includes User, Photo, Album, Event, Group, Page,
Comment, Story, Video, Link, (Note...anything that has data is a node). Every relationship is an edge from
one node to another. Whether you post a photo, join a group, like a page, etc., a new edge is created for
that relationship. All of facebook is then a collection of these nodes and edges. This is because facebook
uses a graph data structure to store its data.

More precisely, a graph is a data structure (V, E) that consists of a collection of vertices V & a collection
of edges E, represented as ordered pairs of vertices (u,v)
In the graph,
V = {0, 1, 2, 3}
E = {(0,1), (0,2), (0,3), (1,2)}
G = {V, E}

Graph Terminology

Adjacency: A vertex is said to be adjacent to another vertex if there is an edge connecting them. Vertices
2 and 3 are not adjacent because there is no edge between them.

Path: A sequence of edges that allows you to go from vertex A to vertex B is called a path. 0-1, 1-2 and
0-2 are paths from vertex 0 to vertex 2.

Directed Graph: A graph in which an edge (u,v) doesn't necessarily mean that there is an edge (v, u) as
well. The edges in such a graph are represented by arrows to show the direction of the edge.

5. Define the types of Graph Traversal methods and explain the same with algorithms and example.

Ans) Two types of graph Traversal


● DFS
● BFS

Depth first Search


Depth first Search or Depth first traversal is a recursive algorithm for searching all the vertices of a graph
or tree data structure. Traversal means visiting all the nodes of a graph.

DFS Algorithm
A standard DFS implementation puts each vertex of the graph into one of two categories:
● Visited
● Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The DFS algorithm works as follows:
● Start by putting any one of the graph's vertices on top of a stack.
● Take the top item of the stack and add it to the visited list.
● Create a list of that vertex's adjacent nodes.
● Add the ones which aren't in the visited list to the top of the stack.
● Keep repeating steps 2 and 3 until the stack is empty.

Breadth First Search


Traversal means visiting all the nodes of a graph. Breadth First Traversal or Breadth First Search is a
recursive algorithm for searching all the vertices of a graph or tree data structure.

BFS Algorithm
A standard BFS implementation puts each vertex of the graph into one of two categories:
● Visited
● Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The algorithm works as follows:
● Start by putting any one of the graph's vertices at the back of a queue.
● Take the front item of the queue and add it to the visited list.
● Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue.
● Keep repeating steps 2 and 3 until the queue is empty.
● The graph might have two different disconnected parts so to make sure that we cover every
vertex, we can also run the BFS algorithm on every node.

You might also like