Data Structure Compelete
Data Structure Compelete
Education
Data Structure
3
Definition
5
Why do we need Data Structures?
As data structures are used to store data in an organized form.
7
Classification of Data Structure
8
Primitive Data Structure
• A primitive data type is pre-defined by the programming language.
The size and type of variable values are specified, and it has no
additional methods.
9
Integer ((2 or 4 bytes))
Floating-point ((4 byte))
Character ((1 byte))
String
pointers etc.
Create
Selection
Updating
Destroy or Delete
10
Non-Primitive Data Structure
• The Data structures that are derived from the primitive data
structures.
• The size and type of variable are specified by the programmer.
• These are not predefined. These are user-defined data types created
by programmers.
•
• These data types are used to store multiple values of same type or
different type.
11
Different between them
12
Linear Data structures:
◦ Data structure where data elements are arranged sequentially or linearly where each and
every element is attached to its previous and next.
◦ we can traverse all the elements in single run only.
◦ Linear data structures are very easy to implement, since the memory of the computer is
also organized in a linear fashion.
◦ Some commonly used linear data structures are Array, Stack, Queue and Linked Lists.
there is only one first element and has only one next element,
there is only one last element and has only one previous element, while
all other elements have a next and a previous element 13
Non-Linear Data structures:
◦ Traversal
◦ Insertion
◦ Selection
◦ Searching
◦ Sorting
◦ Merging
◦ Destroy or Delete
15
Commonly used Data Structures
Let’s first list the most commonly used data structures, and
then we’ll cover them one by one:
1. Arrays
2. Stacks
3. Queues
4. Linked Lists
5. Trees
6. Graphs
Top Data Structure learning sites
https://www.geeksforgeeks.org/
https://www.programiz.com/
https://www.javatpoint.com/data-structure-tutorial
https://www.programiz.com/dsa
https://www.mygreatlearning.com/academy/learn-for-free/courses/data-structures-in-c
Arrays
18
Arrays
Index, define the position of data item in the array. The majority
of languages define the starting index of the array as 0.
Syntax
Datatype Array_Name [Size];
Where,
Datatype : Type of value it can store (Example: int, char, float)
Array_Name: To identify the array.
Size : The maximum number of elements that the array can hold.
Arrays
• Simply, declaration of array is as follows:
• int arr[9] = {40, 55, 63, 17, 22,68,89,97,89};
20
Represent a Linear Array in memory
• The elements of linear array are stored in consecutive memory
locations. It is shown below:
21
Arrays
#include <stdio.h>
int main() {
int values[5] = {9,34,23,4,65};
return 0;
}
Char Array example
#include <stdio.h>
int main()
{
char arr[3] = {'a','b','c'};
printf("Char array Elements are:\n");
int main()
{
char arr[3][10] = {"Geek", "Geeks", "Geeksfor"};
#include <stdio.h>
int main() {
int values[5];
return 0;
}
Arrays types
Single Dimension Array
• Array with one subscript
27
One dimensional array:
An array with only one row or column is called one-dimensional
array.
It is finite collection of n number of elements of same type such
that:
◦ Can be referred by indexing.
◦ The Elements are stored in continuous locations.
◦ Elements x to define one-dimensional array is:
28
Multi dimensional array
29
Multi dimensional array
The array int x[5][10] can store total (5*10) = 50 elements.
Salary[3][4];
This example declares a 2D integer array:
int two_d[3][3];
First Type:
int two_dimension[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70,80,90}
};
Second Type:
34
Advantages of Array:
It is used to represent multiple data items of same type by
using single name.
It can be used to implement other data structures like
stacks, queues, tree, graphs etc.
The Memory allocation for data is done sequentially and
does not engage any extra memory.
Accessing array elements using their index is the fastest
method.
Two-dimensional arrays are used to represent matrices.
35
Disadvantages of Array
We must know in advance the how many elements
are to be stored in array.
Array is static structure. It means that array is of fixed
size. The memory which is allocated to array cannot be
increased or decreased.
Array is fixed size; if we allocate more memory than
requirement then the memory space will be wasted.
The elements of array are stored in consecutive memory
locations. So insertion and deletion are very difficult and
time consuming.
36
Home work
◦ Traversing
◦ Searching
◦ Insertion
◦ Deletion
◦ Sorting
◦ Merging
40
Traversing Arrays
Traversing: It is used to access each data item exactly once so
that it can be processed.
E.g.
We have linear array A as below:
0 1 2 3 4
10 20 30 40 50
Here we will start from beginning and will go till last element and
during this process we will access value of each element exactly
once as below:
A [0] = 10
A [1] = 20
A [2] = 30
A [3] = 40
A [4] = 50
41
Algorithm
Step 5: Exit
Traversing Arrays with For Loops
1 2 3 4 5
10 20 50 30 15
New element to be inserted is 100 and location for insertion is 3. So shift the
elements from 5th location to 3rd location downwards by 1 place.And then
insert 100 at 3rd location. It is shown below:
44
Algorithm
Insertion at the given index of an array
We assume A is an array with N elements. The maximum numbers of elements it can store is
defined by MAX.
#include <stdio.h>
int main() {
int LA[] = {1,3,5,7,8};
int item = 100, k = 2, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Deletion from Array
Deletion: It is used to delete an existing data item from the given collection of data items.
48
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.
Deletion from Array
Update Operation
Algorithm
Consider LA is a linear array with N elements and K is a
positive integer such that K<=N.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
Example
output
Searching in Arrays
Searching: It is used to find out the location of the data item if it exists in the given
collection of data items.
E.g. We have linear array A as below:
1 2 3 4 5
15 50 35 20 25
Linear Search: Suppose item to be searched is 20.We will start from beginning and will compare 20
with each element. This process will continue until element is found or array is finished. Here:
1)Compare 20 with 15
20 # 15, go to next element.
2)Compare 20 with 50
20 # 50, go to next element.
3)Compare 20 with 35
20 #35, go to next element.
4)Compare 20 with 20
20 = 20, so 20 is found and its location is 4.
54
Linear Search
55
#include<stdio.h>
#include<conio.h>
void main()
{
int pos,item,flag=0,i;
int a[10]={10,34,22,55,77,43,22,56,38};
for(i=0;i<10;i++)
printf("%d\t",a[i]);
if(flag==1)
printf("\n The element is in the list and it is in: %d index",pos);
else
printf("\n The element is not found");
getch();
}
Example
Consider LA is a linear array with N elements
and K is a positive integer such that K<=N.
2. Binary
It Search
is a search algorithm that is used to find the position of an element
(target value ) in a sorted array.
58
Working
Case 2 − element > middle, search for the element in the sub-array starting
from middle+1 index to n.
Case 3 − element < middle, search for element in the sub-array starting from
0 index to middle -1.
Example in picture
Let’s find 20 in below array
Step 1 : Find the middle element of array. using , middle = initial_value + end_value / 2 ;
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.
Binary Search
62
Binary Search
63
Searchin
g
64
Sorting:
A Sorting Algorithm is used to rearrange a given array or list elements
according to a comparison operator on the elements.
66
Insertion sort
It finds that both 14 and 33 are already in ascending order. For now, 14
is in sorted sub-list.
Insertion sort moves ahead and compares 33 with 27.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list.
Here we see that the sorted sub-list has only one element 14, and 27 is
greater than 14. Hence, the sorted sub-list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33
with 10.
So we swap them.
However, swapping makes 27 and 10 unsorted.
This process goes on until all the unsorted values are covered in a sorted
sub-list.
Algorithm
After each iteration, the largest element among the unsorted elements is
placed at the end.
begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort
Merging Two Array
Merging: It is used to combine the data items of two arrays into single array .
Start adding each and every element of the first array to the third array (target array).
Then start appending each and every element of the second array to the third array
(target array).
0 1 2 3 4 5
10 40 50 80 95 100
datatype *var_name;
int *ptr;
Pointer
The reason we associate data type to a pointer is that it
knows how many bytes the data is stored in
The first pointer is used to store the address of the variable. And the
second pointer is used to store the address of the first pointer. That is
why they are also known as double pointers.
Syntax:
int **ptr; // declaring double pointers
#include<stdio.h>
int main( )
{
int a = 5;
int *b; //declaring pointer
b = &a; //storing address of a in b pointer.
void geeks()
{
int var = 20;
int main()
{
geeks();
}
#include <stdio.h>
// C program to demonstrate pointer to pointer
int main()
{
int var = 789;
return 0;
}
Stack
A stack is a linear data structure, collection of items of the
same type.
Which follows the First In Last Out (FILO) fashion where the
first element entered is the last one to be popped out or Exit.
86
The order may be LIFO(Last In First Out) or FILO (First In Last Out).
Representation of Stack in Memory
The stack can be implemented into two ways:
88
Using linked list (Dynamic implementation)
A single linked list structure is sufficient to represent any stack. Here, the DATA field is for
the ITEM, and the LINK field is, as usual, to point to the next' item.
Thus, a PUSH operation will add a new node in the front and a POP operation will remove
a node from the front of the list.
Why and when do we use stack
• Stack data structures are useful when the order of actions is important.
• Use a stack when you want to get things out in the reverse order than you
put them in.
• Stack is used to implement algorithms like tower of Hanoi and other graph
algorithms
• Conversion of decimal number to binary.
Conversion of infix expression into prefix and postfix.
Quick sort
90
Application of Stacks
• Reversing: By default a data stack will reverse whatever is input.
• Undo/redo: This approach can be used in editors to implement the undo and redo
functionality.
• Backtracking: Browser back button uses a Stack. This is a process when you need to
access the most recent data element in a series of elements. Once you reach a dead end,
you must backtrack.
• Language Processing: Compiler’ syntax check for matching braces in implemented by
using stack.
Operation on Stacks:
Stack( ): It creates a new stack that is empty. It needs no
parameter and returns an empty stack.
push(item): It adds a new item to the top of the stack.
pop( ): It removes the top item from the stack.
peek( ): It returns the top item from the stack but does not remove
it.
isEmpty( ): It tests whether the stack is empty.
isFull() To check whether a stack is full or not
size( ): It returns the number of items on the stack.
StackTop() is used to find what is at the top of the stack
92
Stack Conditions
93
PUSH Operation
The process of adding one element or item to the stack is
represented by an operation called as the PUSH
operation.
94
PUSH Operation:
The new element is added at the topmost position of the stack.
ALGORITHM:
STACK is the array with N elements. TOP is the pointer to the top of the element of the
array. ITEM to be inserted.
97
PEEK Operation
The process of returning the top item from the stack but does not
remove it called as the POP operation.
ALGORITHM:
STACK is the array with N elements. TOP is the pointer to
the top of the element of the array.
98
Arithmetic Expression
An expression is a combination of operands and operators that after evaluation
results in a single value.
Operand consists of constants and variables.
Operators consists of {, +, -, *, /, ), ] etc.
Expression can be
Infix Expression: If an operator is in between two operands, it is called
infix expression.
Example: a + b, where a and b are operands and + is an operator.
Postfix Expression: If an operator follows the two operands, it is called
postfix expression.
Example: ab +
Prefix Expression: an operator precedes the two operands, it is called
prefix expression.
Example: +ab 99
Ex:
Infix notation: (A-B)*[C/(D+E)+F]
Post-fix notation: AB- CDE +/F +*
Here, we first perform the arithmetic inside the parentheses (A-B) and (D+E). The
division of C/(D+E) must be done prior to the addition with F. After that multiply the
two terms inside the parentheses and bracket.
In the algebraic expression, the order of the operator precedence is given in the below
table:
Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
Multiplication and Division *, /
Push the operands into the stack in the order they appear.
When any operator encounters then pop two topmost operands for executing
the operation.
After the complete execution of expression, the final result remains on the
top of the stack.
For example –
• The big advantage in pre-/postfix notation is that there never arise any
questions like operator precedence.
• Prefix notations and Postfix notations can be evaluated faster than the
infix notation.
• Either format can trivially be turned into a tree for further processing,
• Postfix can be directly translated to code if you use a stack-based
processor or virtual machine
Class Activity:
Out put
1. A*B-C+D
1. A B * C - D +
2. A+B*C-D
2. A B C * + D –
3. ((A/D+C)*(X^Y))
3. A D / C + X Y ^ *
4. A*(B+C)/D-G
4. A B C + * D / G –
5. A*B+(C-D/E)
5. A B * C D E / - +
6. A*(B+C)/D
6. A B C + * D /
7. A+(C^D+E)
7. A C D ^ E + +
8. A^C-D*E
8. A C ^ D E * -
1. A+B*C+D 1. ++A*BCD 1. ABC*D++
2. (A+B)*(C+D) 2. *+AB+CD 2. AB+CD+*
3. A*B+C*D 3. +*AB*CD 3. AB*CD*+
4. A+B+C+D 4. +++ABCD 4. AB+CD++
5. A+B-C*D
6. A-B/C-D
7. A*B-C/D
8. A/B+C/D
Recursion
simple rules:
Input : 3 Input : 2
Output : Output :
Example Program??
Queue
A queue is defined as a linear data structure that is open at both ends and the
operations are performed in First In First Out (FIFO) order.
Queue follows First-In-First-Out methodology, i.e., the data item stored first
will be accessed first.
A real-world example of queue can be a single-lane one-way road,
where the vehicle enters first, exits first.
Queue Representation
As we now understand that in queue, we access both ends for different reasons.
and an existing item is removed at the other end, called the “front”.
Basic Operations
In the queue only two operations are allowed enqueue and dequeue.
peek() − Gets the element at the front of the queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.
Enqueue Operation
The following steps should be taken to enqueue (insert) data into a queue −
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next
empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
Algorithm for enqueue operation
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Enqueue
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow n");
else
{
printf("Insert the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data
where front is pointing and remove the data after access.
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
Dequeue
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow n");
}
else
{
printf("Element deleted from queue is : %d",queue_array[front]);
front = front + 1;
}
}
Display Function
void display()
{
int i;
if(front == - 1)
printf("Queue is empty n");
else
{
printf("Data in Queue are : ");
for(i = front; i <= rear; i++)
printf("%d \n", queue_array[i]);
}
}
Types of Queues
1. Simple Queue
2. Circular Queue
3. Priority Queue
4. De-queue ( Double Ended Queue)
12
Simple Queue
Simple Queue: In simple queue insertion occurs at the rear end
of the list and deletion occurs at the front end of the list.
13
Circular Queue
A circular queue is the extended version of a regular queue where the last
element is connected to the first element.
It is a queue in which all nodes are treated as circular such that the last node
follows the first node.
The main advantage of a circular queue over a simple queue is better memory
utilization. If the last position is full and the first position is empty, we can
insert an element in the first position.
13
Priority Queue
In Priority Queue data with highest priority remove from the Queue
first and second highest priority element after it and so on.
However, if elements with the same priority occur, they are served
according to their order in the queue.
13
Types of dequeue
13
Memory Representation of a queue using
array
13
Application of Queue
13
Linked Lists
A lists is a Linear data structure which can be defined
as a collection of variable or number of data items
called nodes.
The elements are not stored at contiguous memory
locations.
The elements in a linked list are linked using pointers
as shown in the below image:
14
Linked List
In
simple words: a linked list consists of nodes where
each node contains a data field and a reference(link) to the
next node in the list.
Let's see how each node of the linked list is represented. Each node consists:
• A data item
• An address of another node
We wrap both the data item and the next node reference in a struct as:
Understanding the structure of a linked list node is the key to having a grasp on it.
Lists
Types of linked lists:
14
Single linked list
A singly linked list contains two fields in each node - an
information field and the linked field.
•The information field contains the data of that node.
•The link field contains the memory address of the next node.
•There is only one link field in each node, the linked list is called single
linked list.
14
Doubly linked list
It is a linked list in which each node is points both to the next node and
also to the previous node.
In doubly linked list each node contains three parts:
◦ FORW : It is a pointer field that contains the address of the next node
◦ BACK: It is a pointer field that contains the address of the previous node.
◦ INFO: It contains the actual data.
In each node BACK contains NULL, it indicated that it is the first
node in the list.
The node in which FORW contains, NULL indicates that the node is the last node.
14
Single circular linked list
The link field of the last node contains the memory address
of the first node, such a linked list is called circular linked
list.
·In a circular linked list every node is accessible from a
given node.
14
Doubly circular linked list
It has properties of both doubly linked list and circular linked list.
1. Creating
2. Traversing access each element of the linked list
3. Inserting adds a new element to the linked list
4. Deleting removes the existing elements
5. Searching find a node in the linked list
6. Merging two or more linked lists.
15
Creating a linked list
The nodes of a linked list can be created by the following
structure declaration.
struct Node
{
int info;
struct Node *link;
}*node1, node2;
The link field contains a pointer variable that refers the same node structure.
Such a reference is called as Self addressing pointer.
15
Traversing a linked list:
ALGORITHM: TRAVERS (START, P) START contains the address
of the first node.
Another pointer P is temporarily used to visit all the nodes from the
beginning to the end of the linked list.
Step 1: P = START
Step 2: while P != NULL
Step 3: PROCESS data (P) [Fetch the data]
Step 4: P = link(P) [Advance P to next node]
Step 5: End of while
Step 6: Return
15
Traversing a linked list:
Displaying the contents of a linked list is very simple. We keep moving
the temp node to the next one and display its contents.
When temp is NULL, we know that we have reached the end of the
linked list so we get out of the while loop.
15
Inserting node at Front
Inserting a node at the beginning of the linked list
1. Create a node.
2. Fill data into the data field of the new node.
3. Mark its pointer field as NULL
4. Attach this newly created node to START
5. Make the new node as the START node.
15
Inserting node at Front
ALGORITHM: INS_BEG (START, P)
START contains the address of the first node.
15
Inserting node at Last
The new node is always added after the last node of the given
Linked List.
(P)End
Step while
4: data(N) item;
Step
Step 3:
5: N
link(N) new
null
Node;
Step 6: link(P) N
Step 7: Return
75
Inserting node at
• Middle
Allocate memory and store data for new node
• Traverse to node just before the required position of new node
• Change next pointers to include new node in between
Deleting a node
Deleting an item from the linked list:
16
1. Deleting from beginning
• Point head to the second node
16
Non-Linear Data structures
A Non-Linear Data structures is a data structure in which data item is
connected to several other data items.
In a non-linear data structure, single level is not involved. Therefore, we
can’t traverse all the elements in single run only.
1. The tree has one node called root. and hence it does not
have any parent.
2. Each node has one parent only but can have multiple
children.
3. Each node is connected to its children via edge.
Why Tree Data Structure?
Otherdata structures such as arrays, linked list, stack,
and queue are linear data structures that store data
sequentially. In order to perform any operation in a linear
data structure, the time complexity increases with the
increase in the data size. But, it is not acceptable in
today's computational world.
Different
tree data structures allow quicker and easier
access to the data as it is a non-linear data structure.
Tree Applications
Leaf node: The leaf node is a node that does not have any
child node. It is also known as an external node.
Non-leaf node: The non-leaf node is a node that has at
least one child node. It is also known as an internal node.
The main difference between tree and binary tree is that tree
arranges data in a structure similar to a tree in a hierarchical
manner while a binary tree is a type of tree in which a parent
node can have a maximum of two child nodes
3. Binary Search Tree
Ifany node does not have the child, then both link parts
will have NULL values.
Graph
• A graph is a collection of nodes called vertices and the connection
between them called edges.
Example of graph:
6
v2 v5
v1 v3
10
v1 8 11
15
9 v2
v3 v4 v4
Vertices
on the graph are shown as point or circles
and edges are drawn as arcs or line segment.
19
Graph
Types of
Graphs:
◦Directed graph
◦Undirected graph
◦Simple graph
◦Weighted graph
◦Connected graph
◦Non-connected graph
19
Thank you
20