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

Data Structures & Its Application

This document introduces data structures and their applications. It discusses what data and information are, and how data structures provide a systematic way to organize data to use it efficiently. Some examples of commonly used data structures are presented, such as stacks, queues, linked lists, trees and graphs. The document also covers classifying data structures as primitive, non-primitive, and operations like traversing, searching, inserting and deleting. Dynamic memory allocation functions and array operations including traversing, inserting, deleting, searching and sorting are explained. Finally, it briefly discusses polynomials, data types including user-defined types and abstract data types.

Uploaded by

Pushpesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Data Structures & Its Application

This document introduces data structures and their applications. It discusses what data and information are, and how data structures provide a systematic way to organize data to use it efficiently. Some examples of commonly used data structures are presented, such as stacks, queues, linked lists, trees and graphs. The document also covers classifying data structures as primitive, non-primitive, and operations like traversing, searching, inserting and deleting. Dynamic memory allocation functions and array operations including traversing, inserting, deleting, searching and sorting are explained. Finally, it briefly discusses polynomials, data types including user-defined types and abstract data types.

Uploaded by

Pushpesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 138

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

You might also like