Data Structures & Its Application-2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 356

DATA STRUCTURES & ITS

APPLICATION – 21CS34
&
DATA STRUCTURES –
21AR32
INTRODUCTION
INTRODUCTION TO DATA STRUCTURES
What is a Data?
• The quantities, characters or symbols
• On which operations are performed by a computer
• Which may be
• stored
• transmitted in the form of electrical signals
• Recorded on magnetic, optical or mechanical recorded media

• Example: a = b + c
INTRODUCTION TO DATA STRUCTURES
• Data & Information:
• Data: SERUTCURTS ATAD
• Information: DATA STRUCTURES

• If data is arranged in a systematic way then it gets a structure and become


meaningful.
• This meaningful or processed data is called INFORMATION.
• To provide an appropriate way to structure the data, we need to know about
DATA STRUCTURES
INTRODUCTION TO DATA STRUCTURES
• A Data structure is the systematic way to organize data so that it can be used
efficiently.
• Example: Arrays
INTRODUCTION TO DATA STRUCTURES
• Real Life examples of data structure:

• Stack data structure is used in implementing redo and undo feature

• Arrays are used to store an image as a bitmap.

• Graphs are used to store the friendship information on a social networking site
CLASSIFICATION
CLASSIFICATIONS
CLASSIFICATIONS
• Primitive Data Structure:

• Integer: Numeric data. 1,2…

• Character: Single char. ‘a’, ‘A’…

• Floating point: Fractions/ decimal point. 2.1, 2.2..

• Boolean: True/false, binary values

• Strings: Sequence of characters, enclosed in quotes. “Hello”…


CLASSIFICATIONS
• Non - Primitive Data Structure:
• Array: Collection of similar data type in 1 structure
• Array Representation:
CLASSIFICATIONS
• Stack: Last In First Out (LIFO) / First In Last Out (FILO)
CLASSIFICATIONS
• Stack Operations:

PUSH() POP()
CLASSIFICATIONS
• Linked List: Group of nodes in a sequence which has 2 parts: data and address
CLASSIFICATIONS
• Queue: First In First Out (FIFO) to process data
CLASSIFICATIONS
• Queue: First In First Out (FIFO) to process data
CLASSIFICATIONS
Tree: Elements stored on hierarchical relation among data
CLASSIFICATIONS
• Tree:
CLASSIFICATIONS
• Graph: Define connection between different types of data / nodes
DATA STRUCTURE
OPERATIONS
DATA STRUCTURE OPERATIONS
• Traversing: Accessing each record exactly once so that items in the record may
be processes.
• Searching: Finding the location of the record with a given key value or finding
the locations of all records which satisfy one or more conditions.
• Inserting: Adding new record to the data structure.
• Deleting: Removing a record from the data structure.
• Sorting: Arranging the records in some logical order.
• Merging: Combining the records in two different sorted files into a single sorted
file
DYNAMICALLY ALLOCATED
ARRAYS
DYNAMICALLY ALLOCATED ARRAYS
• There are four dynamic memory allocation function:
1. Malloc
2. Calloc
3. Realloc
4. Free
• Malloc:
• Malloc function allocates memory and leaves the allocated memory uninitialized.
• Allocated memory can only be accessed through pointers
• Malloc returns the pointer of type void which can be casting into pointer of any form.
• Malloc returns null pointer if the memory cannot be allocated.
• Syntax:
• void * malloc(size) //actual syntax
• p = (cast type*)malloc(size) //in general
• int *p;
p = (int *)malloc(size)
DYNAMICALLY ALLOCATED ARRAYS
• Malloc:

#include<stdio.h>
#include<stdlib.h>
void main()
{
int n;
printf(“Enter the size of array”);
scanf(“%d”,&n);
int *a = (int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
a[i] = i+1;
}
for(int i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
}
DYNAMICALLY ALLOCATED ARRAYS
• calloc:
• Calloc allocates the memory and initializes all bytes to zero
• Syntax: void* calloc(n, size) //general syntax
datatype *p;
p = (casttype*)calloc(n,sizeof(datatype));
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n;
printf(“Enter the size of array”);
scanf(“%d”,&n);
int *a = (int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
a[i] = i+1;
}
for(int i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
}
DYNAMICALLY ALLOCATED ARRAYS
• realloc:

• If memory allocated using malloc and calloc function is insufficient or more than the required, then we can reallocate the memory using realloc function.

• Syntax: void* realloc(ptr,x) //general syntax


#include<stdio.h>
#include<stdlib.h>
void main()
{
int n;
printf(“Enter the size of array”);
scanf(“%d”,&n);
int *a = (int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
a[i] = i+1;
}
int *b = (int *)realloc(a,n*sizeof(int));
for(int i=0;i<n;i++)
{
printf(“%d”,b[i]);
}
}
DYNAMICALLY ALLOCATED ARRAYS
• free:
• Memory allocated using malloc, calloc function can be released using free
function
• Syntax: free(b);
b = null;//general syntax
ARRAY OPERATIONS
ARRAY OPERATIONS
• There are number of operations that can be performed on arrays.
1. Traversing
2. Inserting
3. Deleting
4. Searching
5. Sorting
ARRAY OPERATIONS - TRAVERSING
• Let A be a array with data {1, 2, 3, 4, 5}
printing all odd/even number’s / counting number of even/odd number’s can be
achieved by traversing the array.
• Traversing: Accessing & Processing each element in a array.
• Algorithm 1 :
1. Set K = LB
2. While K <= UB
3. Apply Process to A[K]
4. Set K = K + 1
5. Exit
ARRAY OPERATIONS - INSERTING
• Let A be collection of data elements stored in the memory of the computer.
Inserting refers to the process of adding new element to the collection.
• Algorithm 1: To add a element
1. Set UB = UB + 1
2. Set A[UB] = Val
3. Exit
ARRAY OPERATIONS - INSERTING
• Algorithm 2: Inserting an element into an linear array at a specified position.
Let A be a linear array with N elements and k is a positive integer such that
k<=N. This algorithm inserts an element into the kth position in A.

Step 1: Initialize counter variable j=N


step 2: run the loop till the while (j>=pos)
a[j+1]=a[j]
j=j-1
end loop
step 3: set a[k]=item
step 4: set n=n+1
step 5: exit
ARRAY OPERATIONS - DELETING
• Algorithm : delete an element from an linear array at a specified position.
Let A be a linear array with N elements and K is a positive integer such that
k<=N. This algorithm deletes an element from the kth position in A

Step 1: Set item = A[k]


step 2: repeat for j=k to n-1
a[j]=a[j+1]
end loop
step 3: set n=n-1
step 5: exit
ARRAY OPERATIONS - SEARCHING
• Algorithm: Linear search
step 1: Let a be an linear array of size n
step 1: Initialize the counter variable i=0
step 2: repeat while (a[i]!=key && i<n)
set i = i+1
end loop
step 3: print key found or not found
step 4: exit
ARRAY OPERATIONS - SEARCHING
• C Program: Linear search
ARRAY OPERATIONS - SEARCHING
• Algorithm: Binary search
Let A be an sorted array with n elements and let k be the key element to be
searched
step 1: Initialize low = 0 high = n-1, mid
step 2: while low<=high
mid = (low+high)/2
if a[mid] = key ‘k’, then print success
else compare key k<a[mid].
If so set high = (mid)-1
else set low = [mid]+1
step 3: print result of search
step 4: exit.
ARRAY OPERATIONS - SEARCHING
• Program in c: Binary search
ARRAY OPERATIONS - SORTING
• Algorithm: Bubble Sort {5,1,4,2,8}
Let A be an array with n elements.
This algorithm sorts the elements in A.
Step 1: Repeat steps 2 and 3 for k=1 to n-1
Step 2: set j = 1
Step 3: for j=1 to j<=n-k
if a[j]>a[j+1] then
swap a[j] and a[j+1]
end if
end for
step 4: exit
POLYNOMIALS
DATA TYPES
DATA TYPE / USER DATA TYPE / ABSTRACT DATA TYPE
Data type:
• Defines a certain domain of values.
• It defines Operations allowed on those values.
• Example: int type:
Takes only integer values
Operations: Addition, subtraction, multiplication, bitwise
• Example: float type:
Takes only floating point values
Operations: Addition, subtraction, multiplication, division
etc.
Bitwise operations are not allowed
DATA TYPE / USER DEFINED / ABSTRACT DATA TYPE
User Defined Data type:
• The operations and values of user defined data type are not specified in the
language but is specified by the user.
• Example: Structure
BY using this structure, we are defining our own data type by
combining other data type.
Struct point {
int x;
int y;
};
DATA TYPE / USER DEFINED / ABSTRACT DATA TYPE
Abstract Data type:
• ADTs are like user defined data types which defines operations on values using
functions without specifying what is there inside the function and how the
operations are performed.
• ADTs are like black box which hides the inner structure and design of the data
type from the user.
• ADT provides Abstraction
SPARSE MATRIX
OR
DEMONSTRATION OF
SPARSE MATRIX WITH
ARRAYS
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Matrix:
• A matrix contains m rows and n columns of elements.
• The total number of elements in such matrix is m*n.
• If m and n are equal, then it is called as square matrix.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Sparse Matrix:
• If the matrix contains a majority of zero entries, then the
matrix is called sparse matrix.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Abstract Data Type of Sparse Matrix:
• ADT SparseMatrix is
objects: a set of triples <row, column, value>, where row and column are
integers and form a unique combination, and value comes from the set item.
functions:
for all a, b € SparseMatrix, x € item, i, j, maxCol, maxRow € index

SparseMatrix Create(maxRow, maxCol)::=


return a SparseMatrix that can hold up to
maxItems = maxRow x maxCol and whose
maximum row size is maxRow and whose
maximum column size is maxCol
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Abstract Data Type of Sparse Matrix:
• ADT SparseMatrix is
objects: a set of triples <row, column, value>, where row and column are
integers and form a unique combination, and value comes from the set item.
functions:
for all a, b € SparseMatrix, x € item, i, j, maxCol, maxRow € index

SparseMatrix Transpose(a)::=
return the matrix produced by interchanging the
row and column value of every triple.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Abstract Data Type of Sparse Matrix:
• ADT SparseMatrix is
objects: a set of triples <row, column, value>, where row and column are integers
and form a unique combination, and value comes from the set item.
functions:
for all a, b € SparseMatrix, x € item, i, j, maxCol, maxRow € index

SparseMatrix Add(a, b)::=


if the dimension of a and b are the same
return the matrix produced by adding
corresponding items, namely those with identical
row and column values.
else return error
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Abstract Data Type of Sparse Matrix:
• ADT SparseMatrix is
objects: a set of triples <row, column, value>, where row and column are integers and
form a unique combination, and value comes from the set item.
functions:
for all a, b € SparseMatrix, x € item, i, j, maxCol, maxRow € index

SparseMatrix Multiply(a, b)::=


if number of columns in a equals number of rows in b
return the matrix d produced by multiplying a by b
according to the formula: d[i][j] = (a[i][k] . b[k][j])
where d(i, j) is the (i, j)th element
else return error
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Representation of Matrix in 2D Arrays:
• Each element is represented as Arr[row][column], where Arr[][] is the 2D array.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Representation of Sparse Matrix in 2D Arrays:
• Each element is represented as Arr[row][column], where Arr[][] is the 2D array.

1 6 0 0 0 0 4 0 5

• When we represent a sparse matrix in this way, there is a wastage of space,


since it contains more of a null values.
• We can use much better representation by storing only non-zero elements.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Representation of Sparse Matrix – Triplet
Representation/Array Representation:
• Before implementing the ADT operations, we will see the representation of
sparse matrix.
• We can represent a element within a matrix by using the triple <row, col, value>
• Hence, an array of triples
can be used to represent a
sparse matrix.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Representation of Sparse Matrix – Triplet
Representation/Array Representation:
• Row indices in Ascending order: Since we want the transpose operation work
efficiently, we should organize the triples in this way.
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Representation of Sparse Matrix – Triplet
Representation/Array Representation:
row col value row col val
A[0] 6 6 8 B[0] 6 6 8
[1] 0 0 15 [1] 0 0 15
[2] 0 3 22 [2] 0 4 91
[3] 0 5 -15 [3] 1 1 11
[4] 1 1 11 [4] 2 1 3
[5] 1 2 3 [5] 2 5 28
[6] 2 3 -6 [6] 3 0 22
[7] 4 0 91 [7] 3 2 -6
[8] 5 2 28 [8] 5 0 -15
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Create operation:
• Sparse Matrix Create(maxRow, maxCol) ::=

#define MAX_TERMS 101


typedef struct {
int col;
int row;
int value;
} term;
term a[MAX_TERMS];
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
row col value row col val
• To transpose a matrix, we must
a[0] 6 6 8 b[0] 6 6 8
interchange the rows & Columns. [1] 0 0 15 [1] 0 0 15
• Each element a[i][j] in the original matrix [2] 0 3 22 [2] 0 4 91
becomes element b[j][i] in the transpose [3] 0 5 -15 [3] 1 1 11
matrix. [4] 1 1 11 [4] 2 1 3
[5] 1 2 3 [5] 2 5 28
• Find all elements in Col 0 and store them [6] 3 0 22
[6] 2 3 -6
in row 0. (Simple Transpose) [7] 3 2 -6
[7] 4 0 91
• for each row i [8] 5 2 28 [8] 5 0 -15
take element <i, j, value> and store it
as element <j, i, value> of the transpose
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
row col val
• for each row i row col value
a[0] 6 6 8 b[0] 6 6 8
take element <i, j, value> and store it
[1] 0 0 15 [1] 0 0 15
as element <j, i, value> of the transpose [2] 0 4 91
[2] 0 3 22
[3] 0 5 -15 [3] 1 1 11
• Elements of transpose are not in order [4] 1 1 11 [4] 2 1 3
[5] 2 5 28
of row. [5] 1 2 3
[6] 3 0 22
• To avoid this, use column indices. [6] 2 3 -6
[7] 3 2 -6
[7] 4 0 91
[8] 5 0 -15
[8] 5 2 28
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
• To transpose a matrix acc to(column index)

• for all elements in column j


place element <i, j, value> in
element <j, i ,value>
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
• void transpose (term a[], term b[]) row col value row col val
{
a[0] 6 6 8 b[0] 6 6 8
int n, i, j, currentb;
n = a[0].value; [1] 0 0 15 [1] 0 0 15
b[0].row = a[0].col; [2] 0 3 22 [2] 0 4 91
b[0].col = a[0].row; [3] 0 5 -15 [3] 1 1 11
b[0].value = n;
if ( n > 0) { [4] 1 1 11 [4] 2 1 3
currentb = 1; [5] 1 2 3 [5] 2 5 28
for (i = 0; i < a[0].col; i++) [6] 2 3 -6 [6] 3 0 22
for (j = 1; j <= n; j++)
[7] 4 0 91 [7] 3 2 -6
if (a[j].col == i) {
b[currentb].row = a[j].col; [8] 5 2 28 [8] 5 0 -15
b[current].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}}}
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
Only for reference
• void transpose (term a[], term b[])
{
int n, i, j, currentb;
cb = 1
n = a[0].value; for i = 1 to col
b[0].row = a[0].col;
b[0].col = a[0].row; for j = 1 to n
b[0].value = n;
if ( n > 0) {
if a(j, c) = = I
currentb = 1; b(cb, r) = a(j, c)
for (i = 0; i < a[0].col; i++)
for (j = 1; j <= n; j++) b(cb, c) = a(j, r)
if (a[j].col == i) {
b[currentb].row = a[j].col;
b(cb, v) = a(j, v)
b[current].col = a[j].row; cb++
b[currentb].value = a[j].value;
currentb++;
}}}
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Transpose operation:
cb = 1
for i = 1 to col a=
for j = 1 to n
if a(j, c) = = i
b(cb, r) = a(j, c)
b(cb, c) = a(j, r)
b(cb, v) = a(j, v)
cb++
DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Fast Transpose operation:
• The previous method for computing transpose mainly includes two for loops,
which runs for (n+1) and (k+1)*n times.

Where n = number of columns


k = number of non zero values.

• Time required to calculate transpose is o(columns.elements)

• To minimize this time, Fast transpose approach is followed.


DEMONSTRATION OF SPARSE MATRIX WITH ARRAYS
Procedure to Compute Fast Transpose operation:
• Assume Compute transpose and store the resultant in
matrix B. Use Fast transpose approach.

• Solution:
Fast transpose approach make use of two additional arrays
1. Row Count array – stores the count of number of elements in each row
2. Starting Position array – Indicates the starting index of each row
STRING OPERATIONS
STRINGS
Strings - Introduction:
• A string is a sequence of characters.
• It includes digits and special characters.
• The number of characters in the string is called length of the string.
• The string with zero characters is empty string or null string.
STRINGS
Storing Strings:
• Strings are stored in three types of structures:
1. Record Oriented Fixed – length structures
2. Variable – length structures
3. Linked Structures
STRINGS
1. Record Oriented Fixed Length Structure:
• In this structure, each line will be stored as a fixed length record.
• Disadvantage:
• Time is wasted reading an entire record if most of the storage consists of blank space
• Certain records may require more space than available.
• When the correction consists of more or fewer characters than the original text, changing
a misspelled word require the entire record to be changed.
• Example: printf(“Data”);
int i; p r i n t f ( “ D a t a “ ) ;
0 15

i n t i ;
16 31
STRINGS
2. Variable Length Storage with Fixed Maximum:
• The storage of variable length strings in memory with fixed length can be done
in two ways
1. One can use a marker such as $$ to signal the end of the string
2. One can list the length of the string as an additional item in the pointer array.

Printf(“Data”);$$ 15 Printf(“Data”);$$
int i;$$ 6 int i;$$

. .
. .
STRINGS
3. Linked Storage:
• Fixed length storages cannot be used for word processing which requires
frequent modifications of the strings, for such applications strings are stored by
means of linked lists.
• Linked list is a linearly ordered sequence of memory cell called nodes.
• Each node contains an item and a link which points to the next node in the list.
• Strings can be stored in linked lists as follows:
• Each memory cell is assigned 1 character or a fixed number of characters.
• Link contained in all nodes gives the address of cell containing the next
character or group of characters.
h a i fo ll ow
Linked storage - 1 character per word Linked storage - 2 character per word
STRINGS
String Operations:
• Substring: Group of consecutive elements in string are called as substrings.
• Accessing a substring from a given string requires
1. Name of the string or the string itself
2. Position of the first character of the substring in the given string
3. Length of substring or position of the last character of the string.
4. Substring operation can be written as: SUBSTRING(string, initial, length)
STRINGS
String Operations:
• Indexing: Also called as pattern matching, refers to finding the position when a
string pattern P first appears in a given string text T
• It can be written as index( text, pattern)
• Concatenation: Let S1 and S2 be strings. Then concatenation of S1 and S2
results in a string which contains characters from S1 followed by characters in S2
• Length: The number of characters in a string is called its length.
STRINGS Reverse string

String Operations – c code:


PATTERN MATCHING
ALGORITHMS
STRINGS
Pattern Matching:
1. Pattern matching using substrings of given text string
2. Pattern matching using table derived from pattern.
3. Pattern matching using KMP
4. Pattern matching by checking end indices first
STRINGS
Pattern matching using substrings of given text string:
• Algorithm:
Let T be the string and P be the pattern string. Let m and n represent the length of T and P Respectively.
Step 1: Set i = 0 and MAX = m – n + 1
Step 2: Repeat Step 3 to 5 while i < MAX
Step 3: Repeat j = 0 to n – 1
if P[j]!=T[i + j]
Then goto Step 5
[End of inner loop]
Step 4: [Success] set index = i and exit
Step 5: Set i = i +1
[end of Step 2 outer loop]
Step 6: [Failure] set index = -1
Step 7: exit
STRINGS
Pattern matching using KMP Algorithm:
• Algorithm: Compute Failure Function
• Define an array (failure) equal to size of pattern
• Set index 0 of array to zero
• Take counter variables as i and j
set i = 0 and j = 1
Compare p[i] = p[j]
if p[i] = p[j]
set Failure [j] = i+1, increment i, increment j
if p[i] ≠ p[j] & if i = 0
set failure[j] = 0 , increment j
if p[i] ≠ p[j] & if i ≠ 0
set i = failure[i - 1] & compare p[i] and p[j] until i = 0 or p[i] = p[j]
STRINGS
Pattern matching using KMP Algorithm:
• Algorithm: Pattern Matching
• Take counter variables as i and j
set i = 0 and j = 0
Compare t[i] = p[j]
if t[i] = p[j]
i++, j++
if t[i] ≠ p[j] & if j = 0
i++
if t[i] ≠ p[j] & if j ≠ 0
set j = failure[j - 1] & increment i if j = 0

Return: i – length(Pattern)
STRINGS
Pattern matching using Table derived from pattern:
• Algorithm:
Step 1: [initialization] Set i=0 and state=q0
Step 2: Repeat steps 3 to 5 while Si ≠P, i<N
Step 3: Read T[i]
Step 4: Set Si+1=F(Si,Ti)
Step 5: Set i=i+1
[end of Step 2 loop]
Step 6: [Successful?]
if Si=p then,
index = i-length(P)+1
else
index=0
[end if]
STRINGS
Pattern Matching by Checking End Indices First:
• Algorithm: Pattern Matching
Step 1: Find length of pattern
Step 2: Take a pointer end_match and set it to the length of pattern – 1
Step 3: Take a pointer start, which points to the beginning of text
If the last character of pattern and character at index end_match of T matches
the begin comparing from first index till all characters match
Or
End of string
if the last character did not match
then increment start pointer
STACK CONCEPT /
INTRODUCTION TO STACK
STACK CONCEPT
Introduction:
• Stack is an ordered list in which insertions (also called as push) and deletions (also called as
pop) are made at one end called top.
• Stack is LIFO structure i.e., Last In First Out.
• It is very useful data structure in C programming
• Stack can be implemented using Linked List or Array
• When stack is empty, then it does not contain any
element inside it.
• Whenever the stack is empty, the position of top is -1.
ARRAY REPRESENTATION
OF STACK
STACK IMPLEMENTATION
Using One Dimensional Array:
stack [ max_stack_size]
max_stack_size: maximum number of entries in the stack.
stack[0] = 1st or bottom element is stored
stack[i-1] = ith element is stored
top = points to the top element in stack
top – 1 = empty stack.
STACK CONCEPT
ADT of stack:
Objects: A finite list with zero or more elements
Functions:
Stack Creates(maxstacksize) :: create an empty stack, whose maximum size = maxstacksize.
Boolean IsFull(stack,maxstacksize) :: if(number of element in stack == maxstacksize)
return true
else return false
Stack push(stack,item) :: if(IsFull(stack))
stackFull
else insert item into top of stack & return
Boolean IsEmpty(stack) :: IsEmpty(stack)
if(stack = =creates(maxstacksize))
return true
else return false

Element pop(stack) :: if (IsEmpty(stack))


return
else remove & return the element at the top of the stack
STACK OPERATIONS
STACK CONCEPT
Push Operation:
STACK CONCEPT
Pop Operation:
STACK IMPLEMENTATION
STACK USING DYNAMIC
ARRAYS
STACK CONCEPT
Stack using Dynamic Arrays:
typedef Struct stack
{
int item;
};
int top;
//use malloc to allocate array dynamically
Struct stack *s;
S = (stack)malloc(sizeof(stack));
Initialize top = -1;
Capacity of the stack, by default = 1
If (top = = capacity – 1), stack is full, then increase the capacity of the stack to twice the old capacity.
if(top = =capacity – 1)
realloc(s, 2 * capacity * sizeof(*stack));
capacity = capacity *2;
STACK CONCEPT
Stack using Dynamic Arrays – c code:
STACK CONCEPT
Stack using Dynamic Arrays – c code:
INFIX TO POSTFIX
CONVERSION
EVALUATION OF POSTFIX
EXPRESSION
RECURSION
RECURSION
Introduction:
• Recursion is a process in which a function calls itself directly or indirectly
• In computer science, recursion is a method of solving a computational problem where the
solution depends on solutions to smaller instances of the same problem.
• Recursion solves such recursive problems by using functions that call themselves from within
their own code.
• Example:
int fun()
{
…..
fun();
}
RECURSION
Introduction:
• Recursion function should satisfy the following two conditions:
1. There must be certain values called base values, for which function does not refer to itself
2. Each time the function does refer to itself, the argument of the function must be closer to a base value.

int fun(int n)
{
if(n==1)
return 1;
else
return 1 + fun(n-1)
}
RECURSION
• Whenever a function is called, its activation record is maintained inside a stack.
int fun(int n)
{
if(n==1)
return 1;
else
return 1 + fun(n-1)
}
Int main()
{
int n = 3;
printf(“%d”, fun(n));
return 0;
}
ACKERMAN FUNCTION
ACKERMANN FUNCTION
• It is a function of two integers m & n
• If m = 0,
then A(m, n) = n+1

• If m ≠ 0 but n = 0,
then A(m, n) = A(m-1, 1)

• If m ≠ 0 and n ≠ 0,
then A(m, n) = A(m-1, A(m, n-1))

Refer class notes for the solved problem


INTRODUCTION TO QUEUE
QUEUES
• Queue is the data structure that is familiar to the queue in the real world.
• It follows FIFO( First In First Out) policy.
• Queue can also be defined as the list or collection in which the insertion(enqueue) is done
from one end known as the rear end or tail of the queue. Deletion(dequeue) is done from
another end known as the front end or the head of the queue.
ARRAY REPRESENTATION
OF QUEUE
ARRAY REPRESENTATION OF QUEUE
• Queue can be easily represented by using linear arrays.
• There are two variables: front & rear, that are implemented in the case of every queue..
• Initially the value of front and rear is -1. This represents empty queue.
• Array representation of a queue containing 5 elements along with the respective values of
front and rear is shown below
LINKED LIST REPRESENTATION OF QUEUE
QUEUE OPERATIONS
QUEUE OPERATIONS
QUEUE INSERTION
QUEUE DELETION
MENU DRIVEN PROGRAM ON QUEUE OPERATION
MENU DRIVEN PROGRAM ON QUEUE OPERATION
MENU DRIVEN PROGRAM ON QUEUE OPERATION
MENU DRIVEN PROGRAM ON QUEUE OPERATION
CIRCULAR QUEUE
CIRCULAR QUEUE
• There was one limitation in the array implementation of queue.
• If the rear reaches to the end position of the queue, then there might be possibility that
some vacant spaces are left in the beginning which cannot be utilized.
• So to overcome such limitations, the concept of the circular queue was introduced.
• A circular queue is similar to a linear queue as it is also based
on the FIFO (First In First Out) Principle,
except that the last position is connected to the
first position in a circular queue that forms a circle.
CIRCULAR QUEUE OPERATIONS
• The following operations can be performed on a circular queue
1. Front: It is used to get the front element from the queue
2. Rear: It is used to get the rear element from the queue
3. enQueue(value): This function is used to insert the new value in the queue. The new value is always
inserted from the rear end
4. deQueue(): This function deletes an element from the queue. The deletion in a queue always takes place
from the front end
CIRCULAR QUEUE OPERATIONS
CIRCULAR QUEUE OPERATIONS – ENQUEUE
• General Steps:
 First, we will check whether the queue is full or not
 Initially the front and rear are set to -1.
 When we insert the first element in a queue, front and rear both are set to 0.
 When we insert a new element, the rear gets incremented. i.e., rear = rear + 1.
• Scenarios in which queue is not full :
 If rear != max -1, then rear will be incremented to mod(maxsize) and the new value will be inserted at the rear end of the queue.
 If front != 0 and rear = max-1, it means that queue is not full. Then set the value of rear to 0 and insert the new element there
• Cases where element cannot be inserted:
 When front = = 0 && rear = max – 1, which means that front is at the first position of the queue and rear is at the last position of the
queue
 Front = = rear +1;
CIRCULAR QUEUE OPERATIONS – DEQUEUE
• General Steps:
 First, we will check whether the queue is empty or not.
 If the queue is empty, we cannot perform the dequeue operation
 When the element is deleted, the value of front gets decremented by 1.
 If there is only one element left which is to be deleted, then the front and rear are reset to -1
CIRCULAR QUEUE USING
DYNAMICALLY
ALLOCATED ARRAY
CIRCULAR QUEUE USING DYNAMICALLY ALLOCATED ARRAY
• Steps for implementing queue dynamically:
 Create a new array of twice the capacity
 Copy second segment i.e., queue[front+1] to queue[capacity-1] to position in new queue beginning at zero
 Copy first segment i.e., queue[0] to queue[rear] to position in new queue beginning at capacity-front-1
 Set rear = capacity – 2
 Set front = 2 * capacity – 1
 Capacity = capacity * 2
• Example:
DEQUES
DEQUE
• Deque is a generalized version of a linear queue.
• Linear queue has some restrictions while performing the insertion and deletion of elements.
• The insertion in the linear queue must happen from the rear end and deletion from the front
end.
• A deque (deck ,dequeue) or Double Ended Queue is a generalized version of Queue data
structure.
• This allows insertion and deletion at both ends (front & rear).
DEQUE
DEQUE
• Operations on Deque:
• Insertion at Rear: Adds an item at the rear of deque
• Insertion at Front: Adds an item at the front of deque
• Deletion at Front: Deletes an item from the front of deque
• Deletion at Rear: Deletes an item from the rear of deque
• In addition to above operations, following operations are also supported:
• getFront(): Gets the front item from the queue
• getRear(): Gets the last item from the queue
• isEmpty(): Checks whether deque is empty or not
• isFull(): Checks whether deque is full or not
DEQUE
• Insertion at the front end:
• The element is inserted from the front end of the queue.
• But before implementing the operation, we have to first check whether the queue is full or
not.
• If the queue is not full, then the element can be inserted from the front end by using the
below conditions.
• If the queue is empty, both rear and front are initialized with 0. Now both will point to the first element.
• Else, check the position of the front. If the front is less than 1, then reinitialize it by front = n – 1
• Else decrement the front by 1
DEQUE
• Insertion at the rear end:
• The element is inserted from the rear end of the queue.
• If the queue is empty, both rear and front are initialized to 0. Now both will point to the first element.
• Otherwise, increment the rear by 1. If the rear is at last index, then instead of increasing it by 1, we have to
make it equal to 0
DEQUE
• Deletion at the front end:
• The element is deleted from the front end of the queue.
• If the queue is empty, i.e., front = -1, it is the underflow condition. If the queue is not full, then
• If the deque ha sonly one element, set rear = -1 & front = -1
• Else if front is at end, set front = 0
• Else increment the front by 1
DEQUE
• Deletion at the front end:
• The element is deleted from the front end of the queue.
• If the queue is empty, i.e., front = -1, it is the underflow condition. If the queue is not full, then
• If the deque ha sonly one element, set rear = -1 & front = -1
• Else if front is at end, set front = 0
• Else increment the front by 1
DEQUE
• Deletion at the rear end:
• The element is deleted from the rear end of the queue.
• If the queue is empty, i.e., front = -1, it is the underflow condition. If the queue is not full, then
• If the deque ha sonly one element, set rear = -1 & front = -1
• Else if rear = 0 (rear at front), then set rear = n – 1
• Else decrement the rear by 1
PRIORITY QUEUE
PRIORITY QUEUE
• It is a special type of queue in which the elements are arranged based on the priority.
• It is a special type of queue data structure in which every element has a priority associated with it.
• Suppose some elements occur with the same priority, They will be arranged according to the FIFO principle
PRIORITY QUEUE
• One way List representation of a Priority queue:
PRIORITY QUEUE
• Array representation of a Priority queue:
PRIORITY QUEUE
• Array representation of a Priority queue:
• Example: Consider the priority queue shown in fig.
a. Describe the structure after
(RRR,3), (SSS,4), (TTT,1), (UUU,4) & (VVV,2) are added to the queue.
B. Describe the structure if, after the preceding insertions, three elements are deleted.
PRIORITY QUEUE
• Array representation of a Priority queue:

a. Describe the structure after


(RRR,3), (SSS,4), (TTT,1), (UUU,4) & (VVV,2) are added
to the queue.
PRIORITY QUEUE
• Array representation of a Priority queue:

B. Describe the structure if, after the preceding insertions, three elements are deleted.
APPLICATION OF QUEUE
Application of Queue – JOB SCHEDULING
• Job Scheduling in computer programming makes use of queue
• Show the queue (sequential queue) for scheduling of the jobs as given below:
• J1, J2, J3 arrive in order…Job J4 arrives after J1 is completed

Front Rear q[0] q[1] q[2] q[3] Comments


0 -1 Queue is empty
0 0 J1 Job J1 arrives
0 1 J1 J2 Job J2 arrives
0 2 J1 J2 J3 Job J3 arrives
1 2 J2 J3 Job J1 Completed
1 3 J2 J3 J4 Job J4 inserted
MULTIPLE STACKS &
QUEUES
Multiple Stacks & Queues
• A single array can be used to implement multiple stacks.
• If we have an array defined as a[max_size] & we want to implement two stacks, then divide the array equally
among two stacks.
0 1 2 3 4 5 6 7 8 9

Stack 2
Stack 1

• First element of stack 1: is at 0


• Last element of stack 2: is at max_size – 1
• First stack grows from: 0
• Now we need a pointer which points to last element of stack 1 & 1st element of stack 2.
• Let us use the pointers as bottom and top, which points to bottom most and top most element respectively.
Multiple Stacks & Queues
• In the case mentioned,
bottom of stack [1] = 0
top of stack [1] = ((max_size)/2) – 1 = > (10/2) - 1 = > 5 - 1 => 4

bottom of stack[2] = top of stack[1] +1 => 4 + 1 => 5


top of stack[2] = max_size – 1 => 10 – 1 => 9
• If we want to implement n stacks, divide the memory into n segments
Multiple Stacks & Queues
• #define max_size
#define max_no_of_stacks 10
int top[max_no_of_stacks]
int bottom[max_no_of_stacks]
int n; // number of stacks entered by user

top[0] = bottom[0] = -1
for(j = 1; j < n; j++)
top[j] = bottom[j] = (max_size/n)*j;
bottom[n] = max_size – 1;

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Stack 0 Stack 1 Stack 2

• Assume max_size = 15
Let no. of stacks = 3
Initialize top[0] = bottom [0] = -1
Top[1] = bottom [1] = 15/3 *1 = 5
top[2] = bottom[2] = 15/3 *2 = 10
if top = bottom, stack = empty
Multiple Stacks & Queues
• Before inserting an element, increment top by 1.
• In this case, top[0] = 4. i.e., top of stack 0 = 4
• Increment top [0] by 1.
• That is, top[0] = 5 & bottom[1] = 5
• If top[i] = bottom[i+1] if top[i] = bottom[i]
then stack i is full then stack is empty
• Top[0] = bottom[1] = > stack[0] is full

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5

Stack 0 Stack 1 Stack 2

• Assume max_size = 15
Let no. of stacks = 3
Initialize top[0] = bottom [0] = 1
Top[1] = bottom [1] = 15/3 *1 = 5
top[2] = bottom[2] = 15/3 *2 = 10
INTRODUCTION TO LINKED
LISTS
INTRODUCTION TO LINKED LISTS
• List : Linear collection of data items
• 2 Ways to maintain a list in memory:
• Arrays
• Linked List
• Linked lists are a way to store data.
• Linked list is a linear collection of data elements called node,
where the linear order is given by means of pointers.
• A linked list is a list made up of nodes that consists of two parts
• Data : This field is used to store data/information
• Link : This field contains the address of the next node in the list
INTRODUCTION TO LINKED LISTS
• Types of Linked List
• Singly Linked List
• Doubly Linked List NULL
• Circular Linked List

Singly Linked List

Circular Linked List

Doubly Linked List


INTRODUCTION TO LINKED LISTS
• How linked lists are different from arrays?
• In an array, all the elements are kept a consecutive memory locations (The array items are stored continuously
next to each other).
• While in a linked list, the elements or nodes may be kept at any location but still connected to each other.
• Inserting a new element or deleting a element from a array is expensive/ is a difficult task. i.e., a separate
memory/room need to be created for the new elements. To create a new room, existing elements have to be
shifted. In the case of deletion, the elements need to be shifted after deleting an element from the array.
• Insertion and deletion operations are easier and efficient in linked list. It provides flexibility in inserting and
deleting a item into & from a given position. The memory can be allocated / deallocated as per requirement.
• Linked lists are preferred mostly when you don’t know the volume of data to be stored. For e.g., In an
employee management system, one cannot use arrays as they are of fixed length (Because any number of new
employees can join). In scenarios like this, linked lists or other dynamic data structure are used as their capacity
can be increased or decreased at run time or as and when required.
SINGLY LINKED LISTS AND
CHAINS
SINGLY LINKED LISTS AND CHAINS
( BAT, CAT, EAT, FAT, HAT, JAT, LAT, MAT, OAT, PAT, RAT, SAT, VAT, WAT)
• Adding or deleting an element from this list give rise to data movement problem.
• An elegant solution of data movement in sequential representation is achieved by using
linked list.

Usual way to draw linked list with node


Singly linked list/ chains

Non sequential list representation (Singly linked list/ chains)


REPRESENTATION OF
LINKED LISTS IN MEMORY
REPRESENTATION OF LINKED LISTS IN MEMORY
CREATION OF STRUCTURE
FOR NODE
CREATION OF STRUCTURE FOR NODE
• struct node
{
int data;
struct node *next;
};
• Example:
struct student
{
char name[10], USN[10];
int sem;
int phno[10];
struct student *link;
}s;
DYNAMIC MEMORY
ALLOCATION
DYNAMIC MEMORY ALLOCATION
• Memory is allocated dynamically using malloc() for structure variables.
• struct *s = (struct student*) malloc (sizeof(struct student))
CREATE A NODE
NODE CREATION
• struct node //struct = keyword to define structure, node = variable name
{
char USN[10], name[10], branch[10], phno[10]; // data of type char
int sem; // data of type int
struct node *link; // create a pointer of type “struct node” to store address.
};
Data Next

typedef struct node *NODE //typecasting the structure into one variable called NODE. NODE contains DATA,
LINK

NODE create() // function


{
NODE x;
x = (NODE)malloc(sizeof(struct node)); // allocate the memory for NODE using malloc. sizeof(struct
node): will be allocated to a newly created node using malloc function.
x -> link = NULL;
return x;
}
NODE CREATION in C
#include<stdio.h>
#include<stdlib.h>

struct node {
int data;
struct node *link;
};

int main()
{
struct node *head = NULL;
head = (struct node *) malloc(sizeof(struct node));

head->data = 45;
head ->link = NULL;

printf(“%d”, head->data);
return 0;
}

OUTPUT: 45
TRAVERSING A LINKED LIST
TRAVERSING A LINKED LIST
• Traversing is the most common operation that is performed in almost every scenario of
singly linked list.
• Traversing is visiting each node of the list once in order to perform some operation on that.
• ptr = head;
while (ptr ! = NULL)
{
ptr = ptr -> link;
}
TRAVERSING A LINKED LIST
• Let LIST be a linked list in memory. This algorithm traverses LIST, applying an operation
PROCESS to each element of LIST. The variable PTR points to the node currently being
processed.

1. Set PTR := START


2. Repeat Steps 3 & 4 while PTR ≠ NULL
3. Apply PROCESS to INFO[PTR]
4. Set PTR := LINK[PTR]
end of step 2
5. Exit
TRAVERSING A LINKED LIST
• Procedure to print the information at each node of a linked list.

Procedure: PRINT(INFO, LINK, START)


This procedure prints the information at each node of the list

1. Set PTR := START


2. Repeat Steps 3 & 4 while PTR ≠ NULL
3. Write: INFO[PTR] C program to Print the data of each node in the list
4. Set PTR := LINK[PTR]
end of step 2
5. Return
TRAVERSING A LINKED LIST
• Procedure to traverse the linked list in order to count the number of elements./ Finds the
number NUM of elements in a linked list

Procedure: COUNT(INFO, LINK, START, NUM)

1. Set NUM := 0
2. Set PTR := START
C program to count the number of elements
3. Repeat Steps 4 & 5 while PTR ≠ NULL
4. Set NUM : = NUM + 1
5. Set PTR := LINK[PTR]
end of step 3
5. Return
INSERTION OF NODE
INSERTING A NODE AT THE END OF LINKED LIST
INSERTING A NODE AT THE END OF LINKED LIST

C program to insert a node at the end of the linked list


INSERTING A NODE AT THE END OF LINKED LIST

void insert_end()
{
NODE temp,ptr;
temp = create();
if(head = = NULL)
{
head = temp;
}
ptr = head;
while(ptr!=NULL)
{
ptr = ptr -> link;
}
ptr->link=temp;
}
INSERTING A NODE AT THE FRONT OF LINKED LIST
INSERTING A NODE AT THE FRONT OF LINKED LIST

C program to insert a node at


the front of the linked list
INSERTING A NODE AT THE FRONT OF LINKED LIST
void insert_front()
{
NODE ptr;
ptr = create();
ptr - > link = head;
head = ptr;
}
INSERTING A NODE TO LINKED LIST BASED ON KEY VALUE

void insert_afterkey()
{
int key;
printf(“Enter the key:\n”);
scanf(“%d”, &key);
NODE temp = create(), NODE cur = first;
if(first = = NULL)
{
printf(“List empty”);
return;
}
while(cur -> data !=key)
{
cur = cur -> link;
}
temp -> link = cur - > link;
cur -> link = temp;
}
DELETION OF NODE
DELETING A NODE FROM THE FRONT OF LINKED LIST

void delete_front()
{
NODE temp;
if(first = = NULL)
{
printf(“The list is empty\n”);
return;
}
temp = first;
first = first ->link;
temp->link = NULL;
free(temp);
temp = NULL;
}
DELETING A NODE FROM THE END OF LINKED LIST
void delete_end()
{
NODE temp, prev= NULL;
if(first = = NULL)
{
printf(“The list is empty\n”);
return;
}
if(first ->link = = NULL)
{
free(first);
first = NULL;
return;
}
temp = first;
while(temp -> link ! = NULL)
{
prev = temp;
temp = temp - > link;
}
prev -> link = NULL;
free(temp);
temp = NULL;
}
DISPLAY ELEMENTS OF
NODE
DISPLAY ELEMENTS OF LINKED LIST

void display()
{
if(first = = NULL)
{
printf(“The list is empty\n”);
return;
}
NODE temp;
temp = first;
while(temp ! = NULL)
{
printf(“%d”, temp - > data);
temp = temp - > link;
}
}
Design, Develop and Implement a menu driven Program in C for the following
operations on
Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch,
Sem, PhNo.
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit

//header file
#include<stdio.h>
#include<stdlib.h>

//creation of structure for node


struct node
{
char usn[10],name[10],branch[10],phno[10];
int sem;
struct node *link;
};
typedef struct node *NODE;
NODE temp, FIRST=NULL;

//Function to create a NODE


NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
x->link=NULL;
return x;
}

//Function to read the information which has to be stored in data field of a


node
void read()
{
temp=getnode();
printf("Enter USN:");
scanf("%s",temp->usn);

printf("Enter Name:");
scanf("%s",temp->name);

printf("Enter Branch:");
scanf("%s",temp->branch);

printf("Enter Phone
Number:");
scanf("%s",temp->phno);

printf("Enter Semester:");
scanf("%d",& temp->sem);
}

//a)Create a SLL of N Students Data by using front insertion.


void create_sll()
{
int i,n;
printf("Enter the number of students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n Enter the details of student %d\n",i);
read();
if(FIRST==NULL)
{
FIRST=temp;
}
else
{
temp->link=FIRST;
FIRST=temp;
}
}
}

//b)Display the status of SLL and count the number of nodes in it


void display_count()
{
int count=0;
temp=FIRST;
printf("Student details:\n");
if(FIRST==NULL)
{
printf("Student detail is
NULL. Count is Zero\n");
}
else
{
printf("\nUSN\tNAME\tBRANCH\tPH NO\tSEM\n");
while(temp->link!=NULL)
{
count++;

printf("%s\t%s\t%s\t%s\t%d\n",temp->usn,temp-
>name,temp->branch,temp->phno,temp-
>sem);
temp=temp->link;
}
count++;

printf("%s\t%s\t%s\t%s\t%d\n",temp->usn,temp-
>name,temp->branch,temp->phno,temp-
>sem);
printf("\n Student count:%d\n",count);
}
return;
}

//d)Insertion at front of SLL


void insert_front()
{
printf("Enter the details of students\n");
read();
if(FIRST==NULL)
{
FIRST=temp;
}
else
{
temp->link=FIRST;
FIRST=temp;
}
}

//c)Insertion at end of SSL


NODE insert_end()
{
NODE last=FIRST;
printf("Enter the details of student\n");
read();
if(FIRST==NULL)
{
FIRST=temp;
}
else
{
while(last->link!=NULL)
{
last=last->link;
}
last->link=temp;
}
return FIRST;
}

//d) deletion at front of SSL


void delete_front()
{
temp=FIRST;
if(FIRST==NULL)
{
printf("Lis
t is
empty");
}
else
{
printf("Deleted elements is %s\n",temp->usn);
FIRST=FIRST->link;
free(temp);
}
return;
}

//c) deletion at end of SSL


void delete_end()
{
NODE last=NULL;
temp=FIRST;
if(FIRST==NULL)
{
printf("Lis
t is empty\
n");
}
else if(FIRST-
>link==NULL)
{
printf("Deleted elemt is %s\n",temp->usn);
free(FIRST);
FIRST=NULL;
}
else
{
while(temp->link!=NULL)
{
last=temp;
temp=temp->link;
}
last->link=NULL;
printf("Deleted elemt is %s\n",temp->usn);
free(temp);
}
return;
}

//main Function
void main()
{
int choice;
while(1)
{
printf(" MENU
\n"); printf("1. Create a SLL of N
Students using front insertion\n"); printf("2. Display from Beginning\
n");
printf("3. Insert at front\n");
printf("4. Insert at end\n");
printf("5. Delete at front\n");
printf("6. Delete at end\n");
printf("7. Exit\n");
printf("

\n"); printf("Enter choice : ");


scanf("%d", &choice);
switch (choice)
{
case 1: create_sll();
break;
case 2: display_count();
break;
case 3: insert_front();
break;
case 4: insert_end();
break;
case 5: delete_front();
break;
case 6: delete_end();
break;
case 7: return;
default:printf("Invalid choice\n");
}
}
}
SEARCHING A LINKED LIST
SEARCHING A LINKED LIST - UNSORTED
• Let LIST be a linked list in memory. Suppose a specific ITEM of information is given. Then we have two
searching algorithms for finding the location LOC of the node where ITEM first appears in the LIST.
1. LIST is Unsorted
2. LIST is Sorted
• List is UNSORTED
Data in the LIST are not sorted
• SEARCH(INFO, LINK, START, ITEM, LOC)
LIST is a linked list in memory. This algorithm finds the location LOC of the node where ITEM first appears
in LIST, or sets LOC = NULL
1. Set PTR := START
2. Repeat step 3 while PTR ≠ NULL
3. if ITEM = INFO[PTR]
set LOC := PTR and exit
Else:
Set PTR := LINK[PTR]
[End of If Structure]
[end of step 2]
4. Set LOC := NULL
5. Exit
SEARCHING A LINKED LIST - UNSORTED

void search()
{
int key, flag = 0;
printf(“Enter the key”);
scanf(“%d”, &key);
NODE cur = first;
while(cur ! = NULL && flag = = 0)
{
if(cur -> data = =key)
{
flag = 1;
}
else
{
cur = cur - > link;
}
}
if (flag = = 1)
{
printf(“key found”);
}
else
{
printf(“Key not found”);
}

}
SEARCHING A LINKED LIST - SORTED
• START is a pointer variable which contains the address of first node. ITEM is the value to be
searched
1. set PTR = START, LOC = 1 // initialize PTR & LOC
2. Repeat step 3 while PTR != NULL
3. If ITEM < INFO[PTR], then
Set PTR = LINK[PTR]
Else if ITEM = INFO[PTR], then
Set LOC = PTR & Exit
Else
Set LOC = NULL, & Exit
End of IF
End of Loop
4. Set LOC= NULL
5. EXIT
SEARCHING A LINKED LIST - SORTED
• Void search()
{
int key, flag = 0;
printf(“ enter key”);
scanf(“%d”, &key);
NODE cur = first;
while(cur!=NULL && flag = =0)
{
if (cur -> data = = key)
{
flag = 1;
}
else if( cur->data > key)
{
break;
}
else
{
cur = cur -> link;
}
}
if (flag = =1) { printf(“key found”);}
else { printf(“Key not found”);}
}
INSERT AFTER KEY IN A
LINKED LIST
Void insert afterkey()
{

While(cur -> data ! = key)


{
cur = cur -> link;
}
temp -> link = cur - > link;
cur -> link = temp;
REVERSE ELEMENTS IN A
LINKED LIST
DOUBLY LINKED LIST
HEADER LINKED LIST
HEADER LINKED LIST
• A header linked list is a linked list which always contains a special node called the header
node, at the beginning of the list.
• Two types of header lists:
A grounded header list: It is a header where the last node contains the null pointer.

Circular header list: It is a header list where last node


points back to the header node
HEADER LINKED LIST
• List pointer START always points to the header node
• The term NODE normally refers to an ordinary node, not the header node, when used with
header lists.
• Thus the first node in header list is the node following the header node
• The location of the first node is LINK[START] and not START as in other ordinary list.
HEADER LINKED LIST
HEADER LINKED LIST
• Header linked lists are frequently used for maintaining polynomials in memory
MEMORY ALLOCATION &
GARBAGE COLLECTION
MEMORY ALLOCATION
SPARSE MATRIX - LINKED
LIST
TREES
INTRODUCTION
INTRODUCTION
• A Tree is a collection of nodes connected by directed / undirected edges.
• A tree is a nonlinear data structure when compared with arrays, linked lists, stacks and
queues.
DEFINITION:
• A tree is a finite set of one or more nodes such that
• There is a specially designated node called root.
• The remaining nodes are partitioned into n >= 0 disjoint set T1,…,Tn, where each of
these sets is a tree. T1,…,Tn are called the subtrees of the root.

• Every node in the tree is the root of some subtree


TERMINOLOGY
TERMINOLOGY
• ROOT:
• The first node from where the tree originates is called root node.
• In any tree, there must be only one root node
• You can never have multiple root nodes in a tree data structure
TERMINOLOGY
• NODE:
• The item of information plus the branches to other nodes
PARENT NODE

NODE NODE

• DEGREE OF A NODE:
• The number of Subtrees of a node / Total number
of children of that node
• DEGREE OF A TREE:
• The maximum of the degree of the
nodes in the tree
TERMINOLOGY
• TERMINAL NODE/LEAF:
• Nodes that have degree zero / node with no successor / elements(node) with no children.

• NON TERMINAL NODE / INTERNAL NODE:


• Nodes that doesn’t belong to terminal node
• Nodes which are not leaves
• Node which has at least one child
TERMINOLOGY
• PARENT:
• The element directly above some node is called its parent./ The node which has a branch
from it to any other node / node with 1 or more children.
• CHILDREN:
• The elements directly under an element are called its children. Node except root node are
child nodes.
• Suppose N is a node in T with left successor S1 and right successor S2, then N is called the
Parent of S1 and S2. Here, S1 is called left child and S2 is called right child of N.
B and C are children of A
G and H are children of C
K is child of G
TERMINOLOGY
• SIBBLINGS:
• Nodes with the same parent. /nodes with same parent.
• EDGE:
• A line drawn from the node N of a T to a successor is called an edge
• Connecting link between two nodes.
• A tree with n number of nodes contains (n-1) number of edges.

B & C are Siblings


D, E & F are siblings
G & H are siblings
I & J are siblings
TERMINOLOGY
• PATH:
• A sequence of consecutive edges from node N to a node M is called path.

Path between nodes A & J is: A-B-


E-J
Path between nodes C & K is: C-G-
K
TERMINOLOGY
• ANCESTORS:
• All the nodes along the path from the root to that node.
• DESCENDANTS:
• The descendants of a node are all the nodes that are
in its subtrees.
TERMINOLOGY
• LEVEL:
• This is defined by letting the root be at level zero. If the node is at level l, Then its children are
at level l+1./ Each step from top to bottom is level of tree.
TERMINOLOGY
• HEIGHT:
• The maximum level of any node in the tree / Maximum depth of all its nodes. / Total number
of edges that lies on the longest path from any leaf node to a particular node is height of that
node.
• HEIGHT OF A TREE:
• Height of root node
• Height of all leaf nodes = 0.
TERMINOLOGY
• DEPTH:
• Total number of edges from root node to a particular node is called as depth of that node.
• DEPTH OF A TREE:
• Total number of edges from root node to a leaf node in the longest path.
• Depth of the root node = 0
TERMINOLOGY - EXAMPLE
A – Root node
B - Parent of E & F
C & D – Siblings of B
E & F –Children's of B
K, L, F, G, M, I, J – External /
Leaf nodes / Leaves
A, B, C, D, E, H – Internal
Nodes
Level of E – 3
Degree of B – 2
Degree of tree – 3
Ancestors of M - A, D, H
Descendants of D – H, I, J, M
REPRESENTATION OF
TREES
LIST REPRESENTATION
• The tree can be represented as list.
• The tree given can be written as the list:
(A(B(E(K,L),F),C(G),D(H(M),I,J)))
• The root comes first, followed by a list of sub-trees
LIST REPRESENTATION
LIST REPRESENTATION
LEFT CHILD RIGHT SIBLING REPRESENTATION
• The below figure show the node structure used in the left child-right sibling representation.
• To convert the given tree into this representation,
1. First node that every node has at most one leftmost
child.
2. At most one closest right sibling.
LEFT CHILD RIGHT SIBLING REPRESENTATION
LEFT CHILD – RIGHT CHILD / DEGREE TWO REPRESENTATION
• Rotate the right sibling pointers in a left child right sibling tree clockwise by 45 degrees.
BINARY TREES
BINARY TREES
• A binary tree T is defined as a finite set of nodes such that,
T is empty or (called as null tree or empty tree)
T consists of a root and two disjoint binary trees called the left subtree and the right
subtree.
• A tree whose elements have at most 2 children is called as binary tree.
• Since each element in a binary tree can have only 2 children, we name them as left and right
child.
• Each node has either 0 child or 1 child or 2 children
TYPES OF BINARY TREES
LEFT SKEWED BINARY TREE
• Binary tree in which only left sub tree is present.
• All the nodes except one node has one and only one child
RIGHT SKEWED BINARY TREE
• Binary tree in which only right sub tree is present
COMPLETE BINARY TREE
• Consider a binary tree T. Each node of T can have at most 2 children’s.
• Accordingly, one can show that the level r of T can have at most
• A tree T is said to be complete if all its levels except possibly the last have the
maximum number of possible nodes,
and if all the nodes at the last level
appear as far left as possible.
• A complete binary tree is a special type of binary tree where all the levels of the
tree are filled completely except the lowest level nodes which are filled from as
left as possible.
FULL BINARY TREE
• A full binary tree of depth ‘k’ is a binary tree of depth k having – 1 nodes, k ≥ 1.
• A binary tree in which every node has either 0 or 2 children.
EXTENDED BINARY TREE
• Extended binary tree is a type of binary tree in which all the null sub tree of the
original tree are replaced with special nodes called external nodes whereas
other nodes are called internal nodes.
PROPERTIES OF BINARY
TREES
PROPERTIES OF BINARY TREE
• (1) The maximum number of nodes on level i of a binary tree is , i ≥ 1.
• (2) The maximum number of nodes in a binary tree of depth k is -1, k ≥ 1.
• (3) For any nonempty binary tree, T, if is the number of leaf nodes and the
number of nodes of degree 2, then = + 1.

=4
= + 1 =4+1=5.
Therefore, total number of leaf
node = 5
REPRESENTATION OF
BINARY TREES
ARRAY REPRESENTATION
LINKED REPRESENTATION
• The problems in array representation are:
It is good for complete binary trees, but more memory is wasted for
skewed and many other binary trees.
The insertion and deletion of nodes from the middle of a tree require the
movement of many nodes to reflect the change in level number of these nodes.
• These problems can be easily overcome by linked representation.
• Each node has three fields,
LeftChild - which contains the address of left subtree
RightChild - which contains the address of right subtree.
Data - which contains the actual information
LINKED REPRESENTATION
• Each node has three fields,
LeftChild - which contains the address of left subtree
RightChild - which contains the address of right subtree.
Data - which contains the actual information
• Structure:
struct node
{
int data;
struct node *left;
struct node *right;
};
typedef struct node *treepointer;
LINKED REPRESENTATION
LINKED REPRESENTATION
BINARY TREE TRAVERSALS
BINARY TREE TRAVERSALS
• Traversing the tree or visiting each node in the tree exactly once
• Types:Pre Order
In Order
Post Order
PREORDER TREE TRAVERSALS
• Preorder is the procedure of visiting a node, traversing left and continue. When you
cannot continue, move right and begin again or move back until you can move right and
resume.
• Recursive function:
Visit the root
Traverse the left subtree in preorder
Traverse the right subtree in preorder
• void preorder (treepointerptr)
{
if (ptr)
{
printf (“%d”,ptr→data);
preorder (ptr→leftchild);
preorder (ptr→rightchild);
}
INORDER TRAVERSAL
• Inorder traversal calls for moving down the tree towards the left until you cannot go
further. Then visit the node, move one node to the right and continue. If no move can
be done, then go back one more node.
• Recursive function:
Traverse the left subtree in inorder
Visit the root
Traverse the right subtree in inorder
• void inorder (treepointerptr)
{
if (ptr)
{
iorder (ptr→leftchild);
printf (“%d”,ptr→data)
inorder (ptr→rightchild);
}
INORDER TRAVERSAL
• void inorder (treepointerptr)
{
if (ptr)
{
iorder (ptr→leftchild);
printf (“%d”,ptr→data)
inorder (ptr→rightchild);
}
}
INORDER TRAVERSAL

• Left root right


• Inorder traversal: A / B * C * D + E
POSTORDER TRAVERSAL
• Postorder traversal calls for moving down the tree towards the left until you can go
no further. Then move to the right node and then visit the node and continue.
• Recursive function:
Traverse the left subtree in postorder
Traverse the right subtree in postorder
Visit the root
void postorder (treepointerptr)
{
if (ptr)
{
postrder (ptr→leftchild);
postorder (ptr→rightchild);
printf (“%d”,ptr→data);
}
}
BINARY SEARCH TREE
BINARY SEARCH TREE
• Binary search tree is a node based binary tree data structure which has the
following properties:
• The left subtree of a node contains only with keys lesser than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the
node’s key.
• The left and right subtree each must also be a binary search tree.
CREATION / INSERTION - BINARY SEARCH TREE
• Create a Binary Search Tree (BST) with following keys:
• 4, 2, 3, 6, 5, 7, 1
DELETION - BINARY SEARCH TREE
• Case 1: Deletion of a leaf node
• Case 2: Deletion of a non leaf node
with 1 Child
• Case 3: Deletion of a non leaf node
with 2 children's
DELETION - BINARY SEARCH TREE
• Case 1: Deletion of a leaf node
• Delete a leaf node with key value 37
DELETION - BINARY SEARCH TREE
• Case 2: Deletion of a non-leaf node with 1 child
• Delete a non-leaf node with key value 35
DELETION - BINARY SEARCH TREE
• Case 3: Deletion of a non-leaf node with 2 children’s
• Delete a non-leaf node with key value 10
SEARCHING - BINARY SEARCH TREE
• Key = = root
• Key < root
Search - Left Subtree
• Key > Root
Search – Right Subtree
THREADED BINARY TREE
ADDITIONAL BINARY TREE
OPERATIONS
GRAPHS
GRAPHS
• A graph G can be defined as an ordered set G(V, E) where V(G) represents the
set of vertices and E(G) represents the set of edges which are used to connect
these vertices.
• A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E),
(E,D), (D,B), (D,A)) is
TERMINOLOGIES
TERMINOLOGIES
• Vertex :
Individual data element of a graph is called as Vertex. Vertex is also
known as node
• Edge:
An edge is a connecting link between two vertices. Edge is also known as
Arc. An edge is represented as (starting Vertex, ending Vertex).
Edges are three types.
Undirected Edge - An undirected edge is a bidirectional edge. If
there is undirected edge between vertices A and B then edge (A , B) is equal to
edge (B , A).
Directed Edge - A directed edge is a unidirectional edge. If there is
directed edge between vertices A and B then edge (A , B) is not equal to edge
(B , A).
Weighted Edge - A weighted edge is a edge with value (cost) on it.
TERMINOLOGIES
• Vertex :

• Edge:

• Undirected Edge

• Directed Edge

• Weighted Edge
TERMINOLOGIES
• Undirected Graph :
A graph with only undirected edges is said to be undirected graph
• Directed Graph:
A graph with only directed edges is said to be directed graph.
• Mixed Graph:
A graph with both undirected and directed edges is said to be mixed
graph.
TERMINOLOGIES
• End vertices or Endpoints:
The two vertices joined by edge are called end vertices (or endpoints) of
that edge.
• Origin:
If a edge is directed, its first endpoint is said to be the origin of it.
• Destination:
If a edge is directed, its first endpoint is said to be the origin of it and
the other endpoint is said to be the destination of that edge.
• Adjacent:
If there is an edge between vertices A and B then both A and B are said
to be adjacent
TERMINOLOGIES
• Outgoing Edge:
A directed edge is said to be outgoing edge on its origin vertex.
• Incoming Edge:
A directed edge is said to be incoming edge on its destination vertex.
• Degree:
Total number of edges connected to a vertex is said to be degree of that
vertex.
• Indegree:
Total number of incoming edges connected to a vertex is said to be
indegree of that vertex.
• Outdegree:
Total number of outgoing edges connected to a vertex is said to be
outdegree of that vertex.
TERMINOLOGIES
• Parallel edges or Multiple edges:
If there are two undirected edges with same end vertices and two
directed edges with same origin and destination, such edges are called parallel
edges or multiple edges.

• Self-loop:
Edge (undirected or directed) is a self-loop if its two endpoints coincide
with each other.
TERMINOLOGIES
• Simple Graph:
A graph is said to be simple if there are no parallel and self loop edges.
• Path:
A path can be defined as the sequence of nodes that are followed in
order to reach some terminal node V from the initial node U.
TERMINOLOGIES
• Closed Path:
A path will be called as closed path if the initial node is same as terminal
node. A path will be closed path if V(origin)=V(Terminal).
• Complete Graph:
A complete graph is the one in which every node is connected with all
other nodes. A complete graph contain n(n-1)/2 edges where n is the number
of nodes in the graph.
•.
TERMINOLOGIES
• Digraph:
A digraph is a directed graph in which each edge of the graph is
associated with some direction and the traversing can be done only in the
specified direction.
GRAPH REPRESENTATIONS
REPRESENTATIONS
• By Graph representation, we simply mean the technique which is to be used in
order to store graph into the computer's memory.
1. Sequential/Matrix Representation
2. Linked Representation
MATRIX REPRESENTATION
• Sequential representation:
In sequential representation, adjacency matrix is used to store the mapping
represented by vertices and edges.
In adjacency matrix, the rows and columns are represented by the graph
vertices.
A graph having n vertices, will have a dimension n x n.
An entry Mij in the adjacency matrix representation of an undirected graph G
will be 1 if there exists an edge between Vi and Vj
MATRIX REPRESENTATION
• Sequential representation:
MATRIX REPRESENTATION
• Sequential representation:
MATRIX REPRESENTATION
• Representation of weighted directed graph is different.
• Instead of filling the entry by 1, the Non- zero entries of the adjacency matrix
are represented by the weight of respective edges.
LIST REPRESENTATION
• Linked Representation
In the linked representation, an adjacency list is used to store the Graph into
the computer's memory.
An adjacency list is maintained for each node present in the graph which stores
the node value and a pointer to the next adjacent node to the respective node.

If all the adjacent nodes are traversed then store the NULL in the pointer field
of last node of the list.
The sum of the lengths of adjacency lists is equal to the twice of the number of
edges present in an undirected graph.
LIST REPRESENTATION
• Linked Representation
In a directed graph, the sum of lengths of all the adjacency lists is equal to the
number of edges present in the graph.
LIST REPRESENTATION
• Linked Representation
In weighted directed graph, each node contains an extra field that is called the
weight of the node.
The adjacency list representation of a directed graph is:
ELEMENTARY GRAPH
OPERATIONS
TRAVERSAL METHODS –
BREADTH FIRST SEARCH
DEPTH FIRST SEARCH
GRAPH TRAVERSAL
• Traversing the graph means examining all the nodes and vertices of the graph.
• There are two standard methods:
1. Breadth First Search
2. Depth First Search
DEPTH FIRST SEARCH - DFS
• Depth first search (DFS) algorithm starts with the initial node of the graph G
and then goes to deeper and deeper until we find the goal node or the node
which has no children.
• The algorithm then backtracks from the dead end towards the most recent
node that is yet to be completely unexplored.
• The data structure used in DFS is stack.
DFS
• DFS:
• Function
BFS
• BFS:
• BFS is a graph traversal algorithm that starts traversing the graph from root
node and explores all the neighboring nodes.
• Then, it selects the nearest node and explore all the unexplored nodes.
• BFS traversal of a graph produces a spanning tree as final result.
• Spanning Tree is a graph without loops.
• Queue data structure with maximum size of total number of vertices in the
graph is used to implement BFS traversal.
BFS
• BFS:
BFS
• BFS:
• Function
INSERTION SORT
INSERTION SORT
INSERTION SORT
INSERTION SORT
INSERTION SORT
INSERTION SORT
INSERTION SORT
RADIX SORT
RADIX SORT
RADIX SORT
RADIX SORT
RADIX SORT
ADDRESS CALCULATION
SORT
HASHING
INTRODUCTION
HASH TABLE ORGANIZATIONS
HASHING FUNCTIONS
STATIC AND DYNAMIC HASHING

You might also like