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

Data Structure Compelete

The document provides an overview of data structures, defining them as organized formats for storing and managing data in programming. It categorizes data structures into primitive and non-primitive types, explains linear and non-linear structures, and discusses common operations such as traversal, insertion, and deletion. Additionally, it covers arrays in detail, including their types, advantages, disadvantages, and basic operations.

Uploaded by

yahiaanawabi86
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Data Structure Compelete

The document provides an overview of data structures, defining them as organized formats for storing and managing data in programming. It categorizes data structures into primitive and non-primitive types, explains linear and non-linear structures, and discusses common operations such as traversal, insertion, and deletion. Additionally, it covers arrays in detail, including their types, advantages, disadvantages, and basic operations.

Uploaded by

yahiaanawabi86
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 191

Benawa Institute of Higher

Education
Data Structure

Course Code:CS.0310 Semester: 3rd


Lecturer: Bilal Ahmad Ayoubi 08 – Feb - 2025
Introduction
to
Data Structures
By:
Bilal Ahmad Ayoubi
Definition

o Data: Collection of raw facts.

o A data structure is a collection of data values and the


relationships between them.

o Data structure is a specialized format for organizing and


storing data in memory that considers not only the elements
stored but also their relationship to each other.

3
Definition

Data Structure must address two fundamental concerns

I. First, how the data will be stored


II. Second, what operations will be performed on it.
Introduction
• Data structure affects the design of both structural
& functional aspects of a program.
Program=algorithm + Data Structure

• Algorithm: is a step-by-step procedure to solve a


particular function.

5
Why do we need Data Structures?
As data structures are used to store data in an organized form.

Based on different scenarios, data needs to be stored in a


specific format. We have a handful of data structures that
cover our need to store data in different formats.
Classification of Data Structure
• Data structure are normally divided into two broad
categories:

• Primitive Data Structure


• Non-Primitive Data Structure

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.

• Primitive data structures have different representations on different


computers.

9
 Integer ((2 or 4 bytes))
 Floating-point ((4 byte))
 Character ((1 byte))
 String
 pointers etc.

Operation on data structure are categorized into


following types:

 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

• A primitive data structure is generally a basic structure that


is usually built into the language, such as an integer, a float.

• A non-primitive data structure is built out of primitive data


structures linked together in meaningful ways, such as a
linked-list, binary search tree, AVL Tree, graph etc.

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:

◦ A Non-Linear Data structures is a data structure in which data item is


connected to several other data items.

◦ Non-Linear data structure may display either a hierarchical relationship or


parent child relationship.

◦ The non-linear data structures are trees and graphs.


Operations:
• The most commonly used operation on data structure are
broadly categorized into following types:

◦ 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

• An array is the simplest and most widely used data structure.


Other data structures like stacks and queues are derived
from arrays.

• Definition: An array is a collection of data that holds


homogeneous (same) values stored in contiguous memory
locations.

• It means an array can contain one type of data only, either


all integer, all float-point number or all character.

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

 int specifies the data type


 “arr” is the name of array
 9 is the number of elements an array can store

20
Represent a Linear Array in memory
• The elements of linear array are stored in consecutive memory
locations. It is shown below:

21
Arrays

◦ The number of elements that can be stored in an array, that


is the size of array or its length is given by the following
equation:
(Upperbound-lowerbound)+1

◦ For the above array it would be (8-0)+1=9,where 0 is the


lower bound of array and 8 is the upper bound of array.
◦ Array can always be read or written through loop.
22
Example

#include <stdio.h>
int main() {
int values[5] = {9,34,23,4,65};

printf("Displaying integers: \n");

for(int i = 0; i < 5; ++i) {


printf("%d\n", values[i]);
}

return 0;
}
Char Array example
#include <stdio.h>

int main()
{
char arr[3] = {'a','b','c'};
printf("Char array Elements are:\n");

for (int i = 0; i < 3; i++)


{
printf("%c\n", arr[i]);
}
return 0;
}
C Program to print Array
#include <stdio.h>

int main()
{
char arr[3][10] = {"Geek", "Geeks", "Geeksfor"};

printf("String array Elements are:\n");

for (int i = 0; i < 3; i++)


{
printf("%s\n", arr[i]);
}
return 0;
}
Example

#include <stdio.h>
int main() {
int values[5];

printf("Enter 5 integers: ");


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}

return 0;
}
Arrays types
 Single Dimension Array
• Array with one subscript

 Two Dimension Array


• Array with two subscripts (Rows and Column)

 Multi Dimension Array


• Array with Multiple subscripts

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

• A multi-dimensional array is an array that has more than


one dimension. It is an array of arrays
• The simplest multi-dimensional array is the 2D array, or
two-dimensional array.

• The number of elements can be obtained by multiplying


number of rows and number of columns.[r][c]

• Data in multi dimensional array are stored in (row major


order)

29
Multi dimensional array
The array int x[5][10] can store total (5*10) = 50 elements.

Similarly array int[3][3][3] can store total(3*3*3) = 27 elements.

Two dimensional array:


Int two_d[10][20];

Three dimensional array:


Int three_d[3][3][3];
Two dimensional array

Definition: An Array of Array is known as 2D array.

A two Dimension array is also known as matrix. Matrix can be


represented as a table of rows and columns.

In a two dimension array we have to give 2 arguments or index


to access a single value.

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:

Int two-d[3][3] = {10,20,30,40,50,60,70,80,90}

A[0] A[1] A[2]


A[0] 10 20 30
A[1] 40 50 60
A[2] 70 80 90
Representation of Two Dimensional Array:

 A is the array of order m x n.To store m*n


number of elements, we need m*n memory
locations.

 The elements should be in contiguous memory


locations.

 There are two methods:


• Row-major method
• Column-major method
33
Two Dimensional Array:
 Row-Major Method: All the first-row elements are stored in sequential
memory locations and then all the second-row elements are stored and
so on. Ex: A[Row][Col]
 Column-Major Method: All the first column elements are stored in
sequential memory locations and then all the second- column elements are
stored and so on. Ex: A [Col][Row]
1000 10 A[0][0] 1000 10 A[0][0]
1002 20 A[0][1] 1002 40 A[1][0]
1004 30 A[0][2] 1004 70 A[2][0]
1006 40 A[1][0] 1006 20 A[0][1]
1008 50 A[1][1] 1008 50 A[1][1]
1010 60 A[1][2] 1010 80 A[2][1]
1012 70 A[2][0] 1012 30 A[0][2]
1014 80 A[2][1] 1014 60 A[1][2]

1016 90 A[2][2] 1016 90 A[2][2]

Row-Major Method Col-Major Method

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

1. Write a C Program to find array Size?

2. Write a C Program to find the largest number in


Array?
Basic operations of Arrays
 Some common operation performed on array are:

◦ 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 1 : [Initialization] Set I = LB

Step 2 : Repeat Step 3 and Step 4 while I < = UB

step 3 : [ processing ] Process the A[I] element

Step 4 : [ Increment the counter ] I = I + 1


[ End of the loop of step 2 ]

Step 5: Exit
Traversing Arrays with For Loops

1. Start a loop from 0 to N-1, where N is the size of array.


for(i = 0; i < N; i++)

2. Access every element of array with help of


arr[index]

3. Print the elements


printf("%d ", arr[i])
Insertion into Array
 Insertion: It is used to add a new data item in the given collection of data
items.
E.g.We have linear array A as below:

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;

printf("The original array elements are :\n");


for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}

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

Update operation refers to updating an existing element


from the array at a given index.

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 update an element available at the


Kth position of LA.

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

printf("\n Enter the element to be searched: ");


scanf("%d",&item);
for(i=0;i<10;i++)
{
if(item==a[i])
{
pos=i;
flag=1;
break; } }

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.

 It used with only sorted list of elements.


 Binary Search first divides a large array into two smaller sub-arrays and
then recursively operate the sub-arrays.
 Binary Search basically reduces the search space to half at each step

58
Working

The binary search algorithm works by comparing the element to be searched


by the middle element of the array

Case 1 − element = middle, the element is found return the index.

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

mid = low + (high - low) / 2

mid = (high + low) / 2


ALGORITHM

Step 1 : Find the middle element of array. using , middle = initial_value + end_value / 2 ;

Step 2 : If middle = element, return ‘element found’ and index.

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.

Types of Sorting Algorithms:


1. Quick Sort
2. Bubble Sort
3. Merge Sort
4. Insertion Sort
5. Selection Sort
6. Heap Sort
7. Radix Sort
8. Bucket Sort
Sortin
g

66
Insertion sort

We take an unsorted array for our example.

Insertion sort compares the first two elements.

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.

And finds that 33 is not in the correct position.

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.

These values are not in a sorted order.

So we swap them.
However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.


We swap them again. By the end of third iteration, we have a sorted
sub-list of 4 items.

This process goes on until all the unsorted values are covered in a sorted
sub-list.
Algorithm

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Insertion sort takes maximum time to sort if elements are sorted in
reverse order. And it takes minimum time (Order of n) when elements
are already sorted.

Uses: Insertion sort is used when number of elements is small. It can


also be useful when input array is almost sorted, only few elements are
misplaced in complete big array.
Bubble Sort
It is a sorting algorithm that compares two adjacent elements and swaps
them until they are in the intended order.
This algorithm is not suitable for large data sets as its average and worst-
case time complexity is quite high.

First Iteration (Compare and Swap)


1. Starting from the first index, compare the first and
the second elements.

2. If the first element is greater than the second element,


they are swapped.

3. Now, compare the second and the third elements.


Swap them if they are not in order.

4. The above process goes on until the last element.


2. Remaining Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the unsorted elements is
placed at the end.

In each iteration, the comparison


takes place up to the
last unsorted element.
The array is sorted when all the unsorted elements are placed at their
correct positions.
Algorithm

In the algorithm given below, suppose arr is an array of n elements. The


assumed swap function in the algorithm will swap the values of given array
elements.

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

We have linear array A as below:

0 1 2 3 4 5
10 40 50 80 95 100

And a linear array B as below:


0 1 2 3
20 35 45 90
After merging merged array C is as below:
0 1 2 3 4 5 6 7 8 9
10 20 35 40 45 50 80 90 95 100
79
Pointers
Pointers are the variables that are used to store the location of
value present in the memory.

Pointer is used to points the address of the value stored


anywhere in the computer memory.

To obtain the value stored at the location is known as


dereferencing the pointer

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

Array of pointers: You can define arrays to hold a number of


pointers.
Pointer to Pointer
It is a pointer which store the address of another pointer.

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.

printf("value of a=%d\n", a);


printf("address of a=%p\n", &a);
printf("Data stored in b which is address of a=%p\n", b);

printf("Address of b=%p\n", &b);


printf("value of a accessing through b =%d",*b);
return 0;
}
Pointer Program
#include <stdio.h>

void geeks()
{
int var = 20;

// declare pointer variable


int *ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}

int main()
{
geeks();
}
#include <stdio.h>
// C program to demonstrate pointer to pointer
int main()
{
int var = 789;

int *ptr1; // pointer for var

int **ptr2; // double pointer for ptr2

ptr1 = &var; // storing address of var in ptr1

ptr2 = &ptr1; // Storing address of ptr1 in ptr2

printf("Value of var = %d\n", var );


printf("Value of var using single pointer = %d\n", *ptr1 );
printf("Value of var using double pointer = %d\n", **ptr2);

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.

 In stack all insertions and deletions are permitted only at one


end of the list.
 When elements are added to stack it grow at one end.
Similarly, when elements are deleted from a stack, it shrinks at
the same end.

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:

1. Using arrays (Static implementation)


2. Using pointer or linked list (Dynamic implementation)
 First we have to allocate a memory block of
sufficient size to accommodate the full capacity
of the stack.

 Then, starting from the first location of the


memory block, the items of the stack can be
stored in a sequential fashion.
 This representation of stack is very easy and
convenient
 it allows the representation of only fixed sized
stacks.

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.

Step 1: if TOP = N-1 then [Check Overflow]


PRINT “ STACK is Full or Overflow”
Exit [End if]

Step 2: TOP = TOP + 1 [Increment the TOP]


Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
95
POP Operation
The process of deleting one element or item from the stack is
represented by an operation called as the POP operation.
When elements are removed continuously from a stack, it
shrinks at same end i.e., top
POP Operation
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.

Step 1: if TOP = 0 then [Check Underflow]


PRINT “ STACK is Empty or Underflow”
Exit
[End if]

Step 2: ITEM = STACK[TOP] [copy and print the TOP Element]


Step 3: TOP = TOP - 1 [Decrement the TOP]
Step 4: Return

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.

Step 1: if TOP = NULL then [Check Underflow]


PRINT “ STACK is Empty or Underflow”
Exit [End if]

Step 2: Return (STACK[TOP]) [Return the top element of the stack]


Step 3:Exit

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 *, /

Addition and Subtraction +,-


Now we need to calculate the value of these arithmetic operations by using a
stack.
The procedure for getting the result is:

Convert the expression in Reverse Polish notation( post-fix notation).

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 execution push the result obtained into the stack.

After the complete execution of expression, the final result remains on the
top of the stack.
For example –

Infix notation: (2+4) * (4+6)


Post-fix notation: 2 4 + 4 6 + *
Result: 60

The stack operations for this expression evaluation is shown below:


Infix, Postfix, Prefix

Infix Postfix Prefix Notes


multiply A and B,
A*B+C/D AB*CD/+ +*AB/CD divide C by D,
add the results
add B and C,
A * (B + C) / D ABC+*D/ /*A+BCD multiply by A,
divide by D
divide C by D,
A * (B + C / D) ABCD/+* *A+B/CD add B,
multiply by A
Converting between these notations

The most straightforward method is to start by inserting


all the implicit brackets that show the order of evaluation e.g.:

Infix Postfix Prefix


( (A * B) + (C / D) ) ( (A B *) (C D /) +) (+ (* A B) (/ C D) )
((A * (B + C) ) / D) ( (A (B C +) *) D /) (/ (* A (+ B C) ) D)
(A * (B + (C / D) ) ) (A (B (C D /) +) *) (* A (+ B (/ C D) ) )
Usage of Postfix and prefix expression:
• Infix notation is easy to read for humans, whereas pre-postfix notation is
easier to parse for a machine.

• The big advantage in pre-/postfix notation is that there never arise any
questions like operator precedence.

• Postfix notations can be used in intermediate code generation in compiler


design.

• 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

The process in which a function calls itself directly or indirectly


is called recursion and the corresponding function is called as
recursive function.

The C programming language supports recursion,


But while using recursion, programmers need to be careful to
define an exit condition from the function, otherwise it will go
into an infinite loop.
Recursive functions are very useful to solve many
mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and
n disks. The objective of the puzzle is to move the entire stack to another
rod, obeying the following

simple rules:

1) Only one disk can be moved at a time.


2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved if it
is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Approach :

Input : 3 Input : 2
Output : Output :

Disk 1 moved from A to C Disk 1 moved from A to B


Disk 2 moved from A to B Disk 2 moved from A to C
Disk 1 moved from C to B Disk 1 moved from B to C
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C

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.

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

In Queue item is inserted at one end called the “rear” or Back.

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.

enqueue() − add (store) an item to the queue.


dequeue() − remove an item from the queue.

Few more functions are required to make the above-mentioned queue


operation efficient.

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

Queues maintain two data pointers, front and rear.


Therefore, its operations are comparatively difficult to implement than
stacks.

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.

The following steps are taken to perform dequeue operation −

Step 1 − Check if the queue is empty.


Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Algorithm for dequeue operation

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

Queue can be of four types:

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

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.

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.

The priority queue supports only comparable elements, which


means that the elements are either arranged in an ascending or
descending order.
13
Dequeue Queue
Double Ended Queue
Dequeue 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).

13
Types of dequeue

There are two types of dequeue


1. Input restricted queue
2. Output restricted queue

 Input restricted Queue


In input restricted queue, insertion operation can be performed at only
one end, while deletion can be performed from both ends.
Output-Restricted Dequeue:

In output restricted queue, deletion operation can be performed at only


one end, while insertion can be performed from both ends.
The image below shows how output restricted dequeue limits removal
at one end.
Memory Representation of a queue using
array
 Queue is represented in memory using linear array.
 Let Queue is a array, two pointer variables called Front and Rear are
maintained.
 The pointer variable FRONT contains the location of the element to be
removed or deleted.
 The pointer variable REAR contains location of the last
element inserted.
 The condition FRONT = NULL indicates that queue is
empty.
 The condition REAR = N-1 indicates that queue is full.

13
Memory Representation of a queue using
array

13
Application of Queue

 Queue of processes in OS.


 Queue of packets in data communication.
 Different types of scheduling algorithms
 Printer server routines
 Key press sequence in keyboard.
 Queues are used in case of uploading images.

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.

 Each nodes is divided into two parts:


◦ The first part contains the information of the element.
◦ The second part contains the memory address of the next node
in the list. Also called Link part.
Linked List
Applications of linked list :

Real world Application


1. Image viewer
2. Previous and next page in a web browser
3. Music Player
4. GPS Navigation

• Linked Lists are used to implement stacks and queues.


• It is used for the various representations of trees and graphs.
• It is used for finding paths in networks
Representation of Linked 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:

◦ Single linked list


◦ Doubly linked list
◦ Single circular linked list
◦ Doubly circular linked list

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.

In which two consecutive elements are linked or connected by


previous and next pointer and the last node points to first node by
next pointer and also the first node points to last node by the
previous pointer.
Operation on Linked List
The operation that are performed on linked
lists are:

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.

The output of this program will be:


Inserting a node into the
linked list
 Inserting a node at the beginning of the
linked list
 Inserting a node at the given position.
 Inserting a node at the end of the linked list.

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.

Step 1: P new Node;


Step 2: data(P) num;
Step 3: link(P) START
Step 4: START P
Step 5: Return

15
Inserting node at Last
The new node is always added after the last node of the given
Linked List.

• Allocate memory for new node


• Store data
• Traverse to last node
• Change next of last node to recently created node

For example if the Linked List is 5->10->15->20->25


and we add an item 30 at the end, then the Linked List becomes
5->10->15->20->25->30. .
15
Inserting node at Last
Inserting node at Last
 ALGORITHM: INS_END (START, P) START contains
the address of the first node.
Step 1: START
Step 2: P START [identify the last node]
while P!= null P
next

(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:

1. Deletion of the first node


2. Deletion of the last node
3. Deletion of the node at the give position

16
1. Deleting from beginning
• Point head to the second node

2. Delete from end


• Traverse to second last element
• Change its next pointer to null
3. Delete from middle
• Traverse to element before the element to be deleted
• Change next pointers to exclude the node from the chain
Deleting node from end

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.

 Non-linear data structures are not easy to implement in comparison to


linear data structure.
 The data items in non-linear data structure represent hierarchical
relationship.
 Each data item is called node.
 The different non-linear data structures are
◦ Trees
◦ Graphs. 16
TREES

A tree is a non-linear data structure which is consisting of


nodes organized as a hierarchy.
 A tree is a collection of nodes that are linked together to
form a hierarchy.
 And these nodes are connected by edges.

 It has one root node and many sub-nodes.


 It is a non-linear data structure compared to arrays, linked
lists, stack and queue.
A tree has the following properties:

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

 Binary Search Trees(BSTs) are used to quickly check whether an


element is present in a set or not.
 Heap is a kind of tree that is used for heap sort.
 Tree data structures are also used to store hierarchical data, and
XML/HTML data, and lead to fast searches, etc.

 A modified version of a tree called Tries is used in modern routers to


store routing information.
 Compilers use a syntax tree to validate the syntax of every program
you write.
 Domain Name Server: To find nearby, reachable computers, it
searches the internet
Tree Applications
 Thefiles and folders that you see in your windows explorer
are stored in the tree format.

 The layout of a webpage is designed in


the tree structure.
 Also, in HTML, the Document Object Model (DOM) forms a
tree structure.
Level : Every node in the tree is assigned a level
the root node is at level 0, children of the root node are at
level number 1. and so on.
 Node : Each data item in a tree is called a node.

 Root node: The topmost node in a tree is known as a root


node.
A root node is a node that does not have any parent.

 Parent of a node: The immediate previous of a node is


known as a parent of a node.
 Child of a node: Any sub node of a given node is called
a child node.

 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.

 Edge : It is a connecting line of two nodes.


 Path: Path is a number of successive (‫)پرله پسی‬edges from
source node to destination node.
 Degree: The number of children of a particular node is
known as a degree.
 Siblings: Nodes with the same parent are called Siblings.
Height of a tree:
The height of a tree is the height of the root node.
or
the count of edges from the root to the deepest node.
Height of a Node
The height of a node is the number of edges from the node to the deepest
leaf node. (ie. the longest path from the node to a leaf node).
Depth of a Node
The depth of a node is the number of edges from the root to the node.
Balanced tree
If the height of the left sub-tree and the right sub-tree for
every node are equal or differs at most by 1, the tree is known
as balanced tree data structure.
Types of Trees in Data Structure

Below are the types of trees in a data structure:


1. General Tree
2. Binary Tree
3. Binary Search Tree
4. AVL Tree
5. Red-Black Tree
1. General Tree

 General tree is a tree in which each node can have


either zero or many child nodes.
 In general tree, there is no limitation on the degree of a
node.
 The tree is the super-set of all other tree
2. Binary Tree
 The binary tree is the kind of tree in which maximum two
children can be found for each parent. The kids are
known as the left kid and right kid.
 This is more popular than other trees. When certain
constraints and characteristics are applied in a Binary
tree, a number of others such as AVL tree, BST (Binary
Search Tree), RBT tree, etc.
Types of Binary Tree

I. Full Binary Tree


II. Perfect Binary Tree
III. Complete Binary Tree
IV. Degenerate or Pathological Tree
V. Skewed Binary Tree
VI. Balanced Binary Tree
I. Full Binary Tree or strictly B Tree
A full Binary tree is a special type of binary tree in which every
parent node/internal node has either two or no children.

II. Perfect Binary Tree


A perfect binary tree is a type of binary tree in which every
internal node has exactly two child nodes and all the leaf
nodes are at the same level.
III. Complete Binary Tree
A complete binary tree is just like a full binary tree, but with two
major differences:

 Every level must be completely filled


 All the leaf elements must lean towards the left.
 The last leaf element might not have a right sibling

i.e. a complete binary tree doesn’t have to be a full binary tree.


IV. Degenerate or Pathological Tree
A degenerate or pathological tree is the tree having a single
child either left or right.
V. Skewed Binary Tree
A skewed binary tree is a pathological/degenerate tree in which the tree is
either dominated by the left nodes or the right nodes. Thus,
there are two types of skewed binary tree:
left-skewed binary tree and right-skewed binary tree.
VI.Balanced Binary Tree

It is a type of binary tree in which the difference between the


height of the left and the right subtree for each node is either
0 or 1.
Difference Between Tree and Binary Tree

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

Binary Search Tree (BST) is a binary tree extension with


several optional restrictions.
1. The left child value of a node should be less than or
equal to the parent value,
2. The right child value should always be greater than or
equal to the parent’s value.
4. AVL Tree

AVL tree is a self-balancing binary search tree in which each


node maintains extra information called a balance factor
whose value is either -1, 0 or +1.

Balance Factor = (Height of Left Subtree - Height of Right Subtree)


4. Red-Black Tree
 Another kind of auto-balancing tree is red-black.

 You’reprobably never going to use red-black trees in your


daily work. They have their real-world applications, but it’s
mostly very low-level stuff, like the Linux kernel.
Rules That Every Red-Black Tree Follows:

1. Red/Black Property: Every node is colored, either red or


black
2. Root Property: The root is black.
3. There are no two adjacent red nodes (A red node cannot
have a red parent or red child).

4. Leaf Property: Every leaf (NIL) is black.


5. new node is always inserted as a RED node.
Advantages of Tree
 The tree reflects the data structural connections.
 The tree is used for hierarchy.
 It offers an efficient search and insertion procedure.
 The trees are flexible. This allows sub trees to be relocated
with minimal effort.
How is a tree represented in the
memory?

 Each node will contain three parts, data part, address of


the left sub tree, and address of the right sub 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.

• Graph is a mathematical non-linear data structure capable of


representing many kind of physical structures.
Graph:

Let's try to understand this through an 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.
Graph

Example of graph:

6
v2 v5
v1 v3
10

v1 8 11
15
9 v2
v3 v4 v4

[a] Directed & [b] Undirected Graph


Weighted Graph 19
Graph
 An edge connects a pair of vertices and many have
weight such as length, cost and another measuring
instrument for according the graph.

 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

You might also like