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

DSA Notes - M.K.G

Uploaded by

shekhawatharsh54
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)
28 views

DSA Notes - M.K.G

Uploaded by

shekhawatharsh54
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/ 18

DSA Notes

lQ) '\,Vhat is a Data Stn1ctm·e?

Ans) A Data Structure is a data object together with the relationships that exists among the
instances & among the individual elements that compose an instance.

2Q) Types of Data Structu!'es and give examp les?

Ans) There are two types of Data Strucmres:

1. Linear Data Structu!'es: A data strucflu·e is said to be linear if the elements fonn a
sequence. It is sequential and continues in natme i.e. access the data in sequential
manner.

hi linear data strucmre we can not insert an item in middle place and it maintains a Ii.near
relationship between its elements

egs: Arrny, Linked list, Stack, Queue, Dequeue etc.

2. Non Linear Data Structures: A data strucmre is said to be non-linear if elements do not
form a sequence. (Not sequential) .

It does not maintain any linear relationship between their elements. Every data item is attached to
several other data item5 in a way that is specific for reflecting relationships. The data ite1m are
not arranged in a sequential stm cture.

egs: Trees, Graphs.

(A data structm·e is lineal' if evel'y ite m is rela ted with next and previous item and it is non
lineal' if it is attac h with many of the items in specific ways to l'eflect rela tionship.)

3Q) \Vhat is a Singly Linked List?

Ans) Singly Linked List is a Sequence of dynamically allocated Storage elements, each
element of which contains a pointer to its successor. A poin ter to the first element of the
Ii.st is called as head and a pointer to the last element of the list is called as tail used to
keep track of the Ii.st elements .

4Q) \Vhat is Doubly Linked List?

Ans) hi Doubly Linked List each element contains two pointers: One Pointer points to its
successor and another to its predecessor (previous element) .It is also called as two way
linked list (traversin g can be done in both directions).

M.K.G
DSA Notes
SQ) Differentiate Array and Linked List?

Ans
Array Linked List
1 .Size of the an-ay is fixed I .Size of the linked list is not fixed
2. Memory is allocated Statically (or) 2. Memo1y is allocated dynamically (at
Dynamically (at run time). runtime).
(If the memo1y is allocated for an a1ny
Stat.ically(at compile time) it is called Static
Arrny and if memo1y is allocated at run
time (dynamically)using operator new it is
called Dynamic Arrny)
3 .Memo1y wastage will be there if all the 3.Memoiy is not wasted as only Required
array posit.ions are not utilized memory is allocated

STACKS: (LIFO DATA STRUCTURE)


6Q) \Vhat is a Stack? (LIFO Data Structure)

Ans) Stack is an ordered collection of items into which items can be inserted and deleted from
only one end called as ' Top"' of the Stack. It is also called as LIFO list. (Last In First
Out).

7Q) \Vhat is Stack Und el"tlow?

Ans) Is Stack is empty and POP operation is perfonned it is not possible to delete the items.
This situation is called Stack Underflow.

SQ) \Vhat is Stack Ovn flow ?

Ans) If Stack is full and PUSH operation is perfonned it is not possible to insert or Push the
new items into the stack. This situation is called Stack Overflow .

9Q) \Vhat are the Applications of Stack?

Ans) i) Stacks are used to convert Infix expression into Postfix .

ii) Stacks are used to Evaluate Postfix Exp1'ession.

iii) Stacks are used in recursion etc.

#include"stdio.h"
#include"conio.h"
#include"my_stack.h"
void main()
{
int ch;
clrscr();
do{
printf("\n Press <1> to Perform PUSH Operation");

M.K.G
DSA Notes
printf("\n Press <2> to perform POP Operation");
printf("\n Press <3> to Display Value of Stack");
printf("\n Press <0> to Exit");
printf("\n Enter your choice-:");
scanf("%d",&ch);
switch(ch)
{
case 1: push();break;
case 2: pop();break;
case 3: display();break;
case 0: printf("\n You select exit....");getch(); exit(0);
default: printf("\n You press wrong choice, exit frm prog....");
getch();exit(0);
}
}while(ch!=0);

getch(
);
}

#include<stdio.h>
#include<process.h>
#include"conio.h"
int stack[10],tos=-1;

void push(void)
{ int val;

if(tos<10)
{
tos++;
printf("\n Enter the value which you want to push into stack-:");
scanf("%d",&val);
stack[tos]=val;
}
else
{
printf("\n STACK IS OVERFLOW MORE THAN SIZE OF STACK..");
getch();
//exit(0);
}

void display(void)
{
// DISPLAY
int t;
t=tos;
while(t>=0)

M.K.G
DSA Notes
{
printf("%d->",stack[t]);
t--;
}

void pop(void)
{ int val;
// deletion
if(tos!=-1)
{
val=stack[tos];
tos--;
printf("\n Deleted vlaue from stack is %d=",val);
}
else
{
printf("\n Stack Underflow...");
getch();
//exit(0);
}
}

M.K.G
DSA Notes

QUEUES: (FIFO DATA STRUCTURE)


llQ) \Vhat is a Queue?

Ans) It is an ordered collection of items into which items can be inserted from one end called
as REAR encl and items are deleted from other end called as FRONT end of the Queue. It
is also called as FIRST IN FIRST OUT (FIFO) LIST).

12Q) \Vhat al'e the applica tions of Queues?

Ans) i) Queues are used in Breadth First Traversal of a Tree.

ii) Queues are used in implementation of Scheduling algorithms of Operating Systems.

13Q) \Vhat is a Circulal' Queue?

Ans) hi Circular Queue, the first position of the a11'3y is kept behind the last position of the
array.

14Q) Diffel'entiate Lineal' Queue ancl Circula1· Queue?

Ans) hi Linear Queue once the queue is full and the deletion is performed, even if first position
is free(vacant) it is not possible to insert the item in that position whereas in Circular
Queue it is possible since the first position is kept behind the last position.

!SQ) \Vhat is Dequeue? (D ouble En clecl Queue)

Ans) hi Double Ended Queue insertion and deletion are possible from both the ends.

M.K.G
DSA Notes
Array is a container which can hold a fix number of items and these items should be of
the same type. Most of the data structures make use of arrays to implement their
algorithms. Following are the important terms to understand the concept of Array.
• Element - Each item stored in an array is called an element.
• Index - Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation:(Storage structure)
Arrays can be declared in various ways in different languages. For illustration, let's take
C array declaration.
Nnm" Fh,m.,ntr.

int
+
array (1 o] = { 35, 33, 42, 10, 14, 19, 27, 44, 26, 31 }
l
Type Size
Arrays can be declared in various ways in different languages. For illustration, let's take
C array declaration.

elements ~ 33 ~F~F,~~~~
index O 1 2 3 4 5 6 7 8 9

Size :10
As per the above ill ustration, following are the important points to be considered.
• Index starts with 0.
• A rray length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example , we can fetch an
element at index 6 as 9 .
Basic Operations
Following are the basic operations supported by an array.
• Traverse - print all the array elements one by one.
• Insertion - Adds an element at the given index.
• Delet ion - Deletes an element at the given index.
• Searc h - Searches an element using the given index or by the value.
• Update - Updates an element at the given index.

M.K.G
DSA Notes
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of
array.
Here, we see a practical implementation of insertion operation, where we add data at
the end of the array -
Algorit hm
Let LA be a Linear Array (unordered) with N elements and K is a positive integer such
that K<=N . Following is the algorithm where ITEM is inserted into the Kth position of LA

1. Start
2. Set J = N
3. Set N = N+1
4. Repeat steps 5 and 6 while J >= K
5. Set LA[J+ 1] = LA[J]
6.SetJ=J-1
7. Set LA[K] = ITEM
8. Stop
Example
Following is the implementation of the above algorithm -

#include <stdio.h>

main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = O, j = n;
printf("The original array elements are :\n");
for(i = O; i<n; i++) {
printf("LA[o/od] = o/od \n", i, LA[i]);
}

M.K.G
DSA Notes
n =n+ 1;
while( j >= k) {
LAU+1] = LAU];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = O; i<n; i++) {
printf("LA(o/od] = o/od \ n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result -
Output
The original array elements are :
LA[O] = 1
LA[1 ] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after insertion :
LA[O] = 1
LA[1 ] = 3
LA[2] = 5
LA[3] = 10
LA[4] = 7
LA[5] = 8
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such
that K<=N. Following is the algorithm to delete an element available at the K th position
of LA.

M.K.G
DSA Notes

#include <stdio.h>

void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
printf("The original array elements are :\n");
for(i = O; i<n; i++) {
printf("LA[o/od] = o/od \ n", i, LA[i]);
}

j = k;
while( j < n) {
LAU- 1] = LAU];
j = j + 1;
}
n = n -1;
printf("The array elements after deleti on :\n");
for(i = O; i<n; i++) {
printf("LA[o/od] = o/od \ n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result -
Output
The original array elements are :
LA[O] = 1
LA[1 ] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after deletion :
LA[O] = 1
LA[1 ] = 3
LA[2] = 7
LA[3] = 8

M.K.G
DSA Notes
Search Operation
You can perform a search for an array element based on its value or its index.
A lgorithm
Consider LA is a linear array with N elements and K is a positive integer such
that K<=N . Following is the algorithm to find an element with a value of ITEM using
sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. SetJ = J +1
6. PRINT J, ITEM
7. Stop
Example
Following is the implementation of the above algorithm -

#include <stdio.h>

void main() {
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = O;
printf("The original array elements are :\n");
for(i = O; i <n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
while( j < n){
if( LAU] == item ) {
break:
}
j =j + 1;
}
printf("Found element %d at position %d\n", item, j+1 );
}
....
W hen we compile and execute the above program, it produces the following result -
Output
The original array elements are :
LA[O] = 1
LA[1] = 3
LA[2] = 5

M.K.G
DSA Notes

LA[3] = 7
LA[4] = 8
Found element 5 at position 3

STACK
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.
Stack Representation
The following diagram depicts a stack and its operations -

Last In - First Out


Push Pop
Dela Element Dela Element

Stac k Stack
A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays, which makes it a fixed size stack implementation.

M.K.G
DSA Notes
QUEUE
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks , 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.

lASTIN FlRSTIN
LAST OUT FlRSTOUT /

A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first. More real-world examples can be seen as queues at the ticket windows and bus-
stops.
Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following
diagram given below tries to explain queue representation as data structure -

In Data Data Data Data Data Out


\. .I

Last In Last Out First In First Out

Queue
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and

- .. '
Structures. For the sake of simplicity, we shall implement queues using one-dimensional array.

M.K.G
DSA Notes
LINKED LIST:

► A dynamic data structure.


► Linear collectio n of da ta items.
► Direction is associa ted w it h it.
► Logical link exits b/w items. Pointers acts as t he logical link.
► Consists of nodes tha t has two fields.
Data field : info of the element.
Next field: next pointer containing the address of next node.

TYPES OF LI NKED LIST:

i. Singly or chain: Single link b/w items.

___1 )1 1- -)_1- -~
ii. Dou bly: There are two links, forward and backwa rd link.

1( )1 1( )1 ~
iii. Circu lar: The last node is again linked to t he first node. These can be singly circular
& dou bly circular list.

ADVANTAGES:

► Linked list use dynam ic memory allocat ion th us allocating memory w hen program
is initialised. List can grow and sh rink as needed. Arrays follow static memory
allocation .Hence t here is was tage of space w hen less elements are declared. There
is possi bility of over flow too bcoz of fixed amount of storage.
► Nodes are stored incont iguously thus insertion and deletion operat ions are easily
implemented.
► Linear data structu res like stack and queues are easily im plemented using linked
list.

DISADVANTAG ES:

► Wastage of memory as pointers requirext ra storage.


► Nodes are inco ntiguously stored thereby increasing time required to access
individua l elements. To access nt h item arrays need a single operat ion wh ile
linked list need to pass t hrough (n-1) it ems.
► Nodes must be read in order from beginning as t hey have inherent sequential
access.

M.K.G
DSA Notes
Types of Linked List
Following are the various types of linked list.
• Simp le L inked L ist - Item navigation is forward only.
• Doubly Linked List - Items can be navigated forward and backward .
• Circu lar L inked List - Last item contains link of the first element as next and
the first element has a link to the last element as previous.
Basic Operations
Following are the basic operations supported by a list.
• Insertion - Add s an element at the beginning of the list.
• Deletion - Deletes an element at the beginning of the list.
• Display - Displays the complete list.
• Search - Searches an element using the given key.
• Delete - Deletes an element using the given key.
Insertion Operation
Adding a new node in linked list is a more than one step activity. W e shall learn this
with diagrams here. First, create a node using the same structure and find the location
where it has to be inserted.

#include"stdio.h"
#include"conio.h"
#include<alloc.h>

typedef struct node


{
int data;
struct node *add;
};

void main()
{
struct node *root,*pre,*new1;
root=pre=new1=NULL;
int val,n,i;

clrscr();
root=(node*)malloc(sizeof(node));
printf("\n Enter value for root node-:");
scanf("%d",&val);
root->data=val;
root->add=NULL;

pre=root;
printf("\n How many node you want to add with root node? -:");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
new1=(node*)malloc(sizeof(node));

M.K.G
DSA Notes
printf("\n Enter vlaue for new node-:");
scanf("%d",&val);
new1->data=val;
new1->add=NULL;
pre->add=new1;
pre=new1;
}

// display items of link list


if(pre==NULL)
{
printf(" \n ROOT NODE NOT FOUNT");
}
else
{
pre=root;
while(pre!=NULL)
{
printf("%d->",pre->data);
pre=pre->add;
}
}
getch();

M.K.G
DSA Notes
NODE

Head Next Next


Data Items Data Items

7r NULL
Next
Data Items

~Noo~
Imagine that we are inserting a node B (NewNode), between A (LeftNode)
and C (RightNode). Then point B.next to C -
NewNode.next - > RightNode;
It should look like this -
NOD NODE

Next
Data Items Nex::_'-- - - - - - - -r=: Data Items

7r NULL
Next
Data Hems

~•" rlODE
Now, the next node at the left should point to the new node.
LeftNode.next -> NewNode;
NOOE

Hoad
Data Items
Next ... . ... Data Items
Next

_) 7r NULL
Next
Data Items

Nr,wNOOI:
This will put the new node in the middle of the two. The new list should look like this -
NuuL NODt

HOi!d Next Next


_ Dato ltems Dato Items Data Items

New NODE 7r NULL

M.K.G
DSA Notes

Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial
representation. First, locate the target node to be removed, by using searching
algorithms.
r-.vOE NOOE.

Head Next Next Next


_ Dataltems Data Items Data Items

t <W'' NOOE
NULL
The left (previous) node of the target node now should point to the next node of the
target node -
LeftNode.next - > TargetNode.next;
IIOOE

Head Next
Data Items • Data Items Data Items

l • NOOE
NULL
This will remove the link that was pointing to the target node. Now, using the following
code, we will remove what the target node is pointing at.
TargetNode.next - > NULL;
NOOc; "ODE
Hoad Next
_ Dataltems Data Items _.. Data Items

Tar • NOOE
NULL
We need to use the deleted node. We can keep that in memory otherwise we can
simply deallocate memory and wipe off the target node completely.
NOOE 1"00

-
Head
Data Items
Next
Data Items
Next

7-r NULL

M.K.G
DSA Notes

hat is a queue in data-structu re?

ueue is an abst ract data structu re, somewha t similar to stack. In contrast to st ack, queue is
pened at bot h end . One end is always used to insert dat a enqueue and the other is used to remove
ata dequeue. Queue fo llows First-In-First-Out met hodology, i.e., t he data item stored f irst will be
accessed first.
hy do we use queues?

s queues fo llows FIFO met hod, they are used when we need to work on data -it ems in exact
equence of their arrival. Every operating system maintains queues of various processes. Priority
ueues and breadth f irst traversal of graphs are some examples of queues.

hat operations can be performed on Queues?

he below operations ca n be performed on a stack -

• enqueue - adds an item to rear of t he queue

• dequeue - removes the item from front of the queue

• peek - gives va lue of front item without removing it

• isempty - checks if stack is empty

• isfull - checks if stack is fu ll


M.K.G

You might also like