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

DSA in C

The document provides an extensive overview of data structures, including definitions, types, and complexities, as well as specific modules on arrays, stacks, queues, and linked lists. It covers operations such as insertion, deletion, and traversal for various data structures, along with algorithms for expression conversion and evaluation. Additionally, it discusses the use of pointers, memory representation, and the applications of these data structures in programming.

Uploaded by

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

DSA in C

The document provides an extensive overview of data structures, including definitions, types, and complexities, as well as specific modules on arrays, stacks, queues, and linked lists. It covers operations such as insertion, deletion, and traversal for various data structures, along with algorithms for expression conversion and evaluation. Additionally, it discusses the use of pointers, memory representation, and the applications of these data structures in programming.

Uploaded by

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

Module I: Introduction to Data Structures: 12 Session Topic

Definition, Types. Algorithm design, Complexity, Time-Space Tradeoffs. Use of


pointers in data structures. Array Definition and Analysis, Representation of Linear
Arrays in Memory, Traversing of Linear Arrays, Insertion and Deletion, Single
Dimensional Arrays, Two Dimensional Arrays, Multidimensional Arrays, Function
Associated with Arrays, Character String in C, Character String Operations, Arrays as
parameters, Implementing One Dimensional Array, Sparse matrix.
Module II: Stacks and Queues: 12 Session Topic
Definition, Array representation of stacks, Operations Associated with Stacks- Push
& Pop, Polish expressions, Conversion of infix to postfix, infix to prefix (and vice
versa), Application of stacks recursion, polish expression and their compilation,
conversion of infix expression to prefix and postfix expression, Tower of Hanoi
problem. Queue: Definition, Representation of Queues, Operations of queues- Insert,
Delete, Priority Queues, Circular Queue, Deque.
Module III: Programming with Linked Lists : 16 Session Topic
Introduction to Singly linked lists: Representation of linked lists in memory,
Traversing, Searching, Insertion into, Deletion from linked list, Garbage collection
and compaction, doubly linked list, operations on doubly linked list, circular linked
list, operations on circular linked list, generalized list. Applications of Linked List-
Polynomial representation using linked list and basic operation. Stack and queue
implementation using linked list.
MODULE 1
INTRODUCTION TO DATA STRUCTURE

Definition: - Data structure refers to the set of rules that are required to perform any
operation on the program

Types of Data Structure: -


1) Primitive Data Structure: - This includes integer, character, float, pointer
2) Non-Primitive Data Structure: - This has further 2 classifications: -
a) Linear Data Structure (Array, Linked-List, Stack, Queue)
b) Non-Linear Data structure (Trees, Graphs)
Complexity: - It refers to the rate at which storage of the problem or time consumed
by the problem increases as a function of problem size.
Two ways to categories complexity of a problem are: -
 Space Complexity: -It refers to the amount of space a problem is needed for
completion of task. We can find out the space complexity by finding out how
much space a problem is taking by finding out that how much memory will be
consumed by the instructions and by the variables used.
 Time Complexity: - It refers to the time taken by the machine to execute the
problem. Calculation of exact time is very difficult so we calculate the time
taken by the machine by using asymptotic notations
o Big ‘O’ Notation: -The given function f(n) can be expressed by big ‘O’
notation as follows. f(n) = O (g(n)) if and only if there exist the +ve
const. ‘C’ and no such that f(n) ≤ C * g(n) for all n ≥ no.
o Omega Notation: -The function f(n) = Ω(g(n)) if and only if there exist
the +ve const C and no such that f(n) ≥ C * g(n) for all n ≥ no
o Theta Notation: -The function f(n) = θ(g(n)) if and only if there exist 3
+ve const ‘C1’ , ‘C2’ and no such that C1 * g(n)≤ f(n) ≤ C2 * g(n)
Big ‘O’ is the upper bond, theta is average bond and omega is the lower
bond.

TIME SPACE TRADE OFF: -


There may be more than one approach (or algorithm) to solve a problem. The best
algorithm (or program) to solve a given problem is one that requires less space in
memory and takes less time to complete its execution. But in practice, it is not
always possible to achieve both objectives. One algorithm may require more space
but less time to complete its execution while the other algorithm requires less time
space but takes more time to complete its execution. Thus, we may have to
sacrifice one at the cost of the other. If the space is our constraint, then we must
choose a program that requires less space at the cost of more execution time. On
the other hand, if time is our constraint such as in real time system, we must
choose a program that takes less time to complete its execution at the cost of more
space.

USE OF POINTER IN DATA STRUCTURE: -


A pointer is a variable in C language which stores the address of address of other
variables. This variable can be of type int, char, array, function, or any other pointer.

ARRAY DEFINATION AND ANALYSIS: -


Array is a collection of finite, ordered and collection of homogeneous type of data
elements.
Linear Array: -If one subscript is required to refer all the elements in an array then
this is called Linear array or one-dimensional array.

Operations of array: -

1. TRAVERSAL
This operation is used to visit all the elements of the array.
Void traverse (int a[], int n)
{
int i;
for(i=0; i<n; i++)
Printf(“%d”,a[i]);
}
2. INSERTION

Inserting the array at the end position can be done easily, but to insert at the
middle of the array we have to move the element to create a vacant position to
insert the new element.
int insert (int a[], int n, int pos, int ele)
{
int i;
for(i=n-1; i>=pos-1; i--)
{
a[i+1] = a[i];
}
a[pos-1] = ele;
n++;
return(n);
}
3. DELETION
Deleting an element at the end of the array can be done easily by only decreasing
the array size by 1.
But deleting an element at the middle of the array require that each subsequent
element from the position where to be deleted should be moved to fill up the array.
int delete (int a[], int n, int pos)
{
for (i = pos-1; i<n-1; i++)
{
a[i] = a[i+1];
} n- - ;
return(0);
}

Memory Representation of 2D Array


- The array having two subscript is called as 2D array.
- In 2D array the elements are stored in contiguous memory location as in single
dimensional array.
- There are 2 ways of storing any matrix in memory.
1. Row-major order
2. Column-major order
Row-major Order
In row-major order the row elements are focused first that means elements of
matrix are stored on a row-by-row basis.
Column-major Order
In column major order the column elements are focused first that means elements
of the matrix are stored in column-by-column basis.

Address Calculation of Matrix in Memory


Row-major order
Suppose a [u1] [u2] is a 2D array u1 = no. of row
u2 = no. of column
Address of a[i][j] = b+(i x u2 + j) x w
Column-major order
Address of a[i][j] = b + (j x u1 + i) x w

Sparse matrices
Matrix with relatively a high proportion of zero entries are called sparse matrix. In
other words, the sparse matrix can be defined as the matrix that has a greater
number of zero elements than the non-zero elements.
Benefits of using the sparse matrix
i)Storage - We know that a sparse matrix contains lesser non-zero elements than
zero, so less memory can be used to store elements. It evaluates only the non-zero
elements.
ii)Computing time: In the case of searching in sparse matrix, we need to traverse
only the non-zero elements rather than traversing all the sparse matrix elements. It
saves computing time by logically designing a data structure traversing non-zero
elements.
Representation of sparse matrix
There are two ways to represent the sparse matrix that are listed as follows -
o Array representation
o Linked list representation

Array representation of the sparse matrix


Representing a sparse matrix by a 2D array leads to the wastage of lots of memory.
This is because zeroes in the matrix are of no use, so storing zeroes with non-zero
elements is wastage of memory. To avoid such wastage, we can store only non-zero
elements. If we store only non-zero elements, it reduces the traversal time and the
storage space.
2D array is used to represent a sparse matrix in which there are three rows named
as
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)
MODULE 2
STACKS AND QUEUES

Stack is a linear data structure in which an element may be inserted or deleted at


one end called TOP of the stack.
 That means the elements are removed from a stack in the reverse order of that in
which they were inserted into the stack.
 Stack is called LIFO (Last-in-first-Out) Str. i.e. the item just inserted is deleted first.
 There are 2 basic operations associated with stack
1. Push :- This operation is used to insert an element into stack.
2. Pop :- This operation is used to delete an element from stack

Condition also arise :


1. Overflow: - When a stack is full and we are attempting a push operation, overflow
condition arises.
2. Underflow: - When a stack is empty, and we are attempting a pop operation then
underflow condition arises.

Representation of Stack in memory


A stack may be represented in the memory in two ways:
1. Using one dimensional array i.e. Array representation of Stack.
2. Using single linked list i.e. Linked list representation of stack.
Array Representation of Stack :
To implement a stack in memory, we need a pointer variable called TOP that hold
the index of the top element of the stack, a linear array to hold the elements of the
stack and a variable MAXSTK which contain the size of the stack.
INSERTION IN STACK (PUSH OPERATION)
This operation is used to insert an element in stack at the TOP of the stack.
Algorithm :-
PUSH (STACK, TOP, MAXSTK, ITEM)
This procedure pushes an item into stack.
1. If TOP = 0 the print Underflow and Return.
2. Set ITEM = STACK[TOP] (Assigns TOP element to ITEM)
3. Set TOP = TOP-1 (Decreases TOP by 1)
4. Return
( Where Stack = Stack is a list of linear structure
TOP= pointer variable which contain n the location of Top element of the stack
MAXSTK= variable which contain size of the stack
ITEM= Item to be inserted)

DELETION IN STACK (POP OPERATION)


This operation is used to delete an element from stack.
Algorithm :-
POP(STACK, TOP, ITEM) This procedure deletes the top element of STACK and
assigns it to the variable ITEM. 1. If TOP = 0 the print Underflow and Return. 2. Set
ITEM = STACK[TOP] (Assigns TOP element to ITEM) 3. Set TOP = TOP-1 (Decreases
TOP by 1) 4. Return

ARITHMETIC EXPRESSION
There are 3 notation to represent an arithmetic expression.
1. Infix notation
2. Prefix notation
3. Postfix notation

1. INFIX NOTATION
• The conventional way of writing an expression is called as infix. Ex: A+B, C+D,
E*F, G/M etc.
• Here the notation is <Operand><Operator><Operand>
• This is called infix because the operators come in between the operands.
2. PREFIX NOTATION
• This notation is also known as “POLISH NOTATION”
• Here the notation is <Operator><Operand><Operand>
• Ex: +AB, -CD, *EF, /GH

3. POSTFIX NOTATION
• This notation is called as postfix or suffix notation where operator is suffixed by
operand.
• Here the notation is <Operand ><Operand><Operator>
• Ex: AB+, CD-, EF*, GH/
• This notation is also known as “ REVERSE POLISH NOTATION.”
CONVERSION FROM INFIX TO POSTFIX EXPRESSION
Algorithm:
POLISH(Q,P)
Q is an arithmetic expression written in infix notation. This algorithm finds the
equivalent postfix expression P.
1. Push “ ( ” onto stack and add “ ) ” to the end of Q.
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the
STACK is empty.
3. If an operand is encountered, add it top.
4. If a left parenthesis is encountered, push it onto stack.
5. If an operator X is encountered, then:
a) Repeatedly POP from STACK and add to P each operator (on the top of the STACK)
which has the same precedence as or higher precedence than the operator X .
b) Add the operator X t
CONVERSION FROM INFIX TO POSTFIX EXPRESSION
Algorithm:
POLISH(Q,P)
Q is an arithmetic expression written in infix notation. This algorithm finds the
equivalent postfix expression P.
1. Push “ ( ” onto stack and add “ ) ” to the end of Q.
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the
STACK is empty.
3. If an operand is encountered, add it top.
4. If a left parenthesis is encountered, push it onto stack.
5. If an operator X is encountered, then:
a) Repeatedly POP from STACK and add to P each operator (on the top of the STACK)
which has the same precedence as or higher precedence than the operator X .
b) Add the operator X t
EVALUATION OF POSTFIX EXPRESSION
Algorithm:
This algorithm finds the value of an arithmetic expression P written in Postfix
notation.
1. Add a right parenthesis “ ) ” at the end of P.
2. Scan P from left to right and repeat steps 3 and 4 for each element of P until the “
) ” is encountered.
3. If an operand is encountered, put it on STACK.
4. If an operator X is encountered then:
a) Remove the two top element of STACK, where A is top element and B is the next-
to-top element.
b) Evaluate B X A.
c) Place the result of (b) on STACK.
[End of if str.]
5. Set value equal to the top element on STACK.
6. Exit

APPLICATIONS OF STACK:
 Recursion process uses stack for its implementation.
 Quick sort uses stack for sorting the elements.
 Evaluation of antithetic expression can be sone by using STACK.
 Conversion from infix to postfix expression
 Evaluation of postfix expression
 Conversion from infix to prefix expression
 Evaluation of prefix expression.
 Backtracking
 Keeptrack of post-visited (history of a web- browsing)

IMPLEMENTATION OF RECURSION
A function is said to be Recursive function if it call itself or it call a function such that
the function call back the original function. This concept is called as Recursion. The
Recursive function has two properties.

I. The function should have a base condition.


II. The function should come closer towards the base condition.
The following is one of the example of recursive function which is described below.
Factorial of a no. using Recursion
The factorial of a no. ‘n’ is the product of positive integers from 1 to n.
n ! = 1 X 2 X 3 X . . . . . . . . . . . . .X (n-) X n Physically proved n ! = n X (n-1) ! The
factorial function can be defined as follows.
I. If n=0 then n ! = 1
II. If n>0 then n ! = n.(n-1) !
The factorial algorithm is given below factorial ( fact , n )
This procedure calculates n! and returns the value in the variable fact.
1. If n=0 then fact=1 and Return.
2. Call factorial (fact, n-1)
3. Set fact = fact*n
4. Return
QUEUE
• Queue is a linear data structure or sequential data structure where insertion take
place at one end and deletion take place at the other end.
• The insertion end of Queue is called rear end and deletion end is called front end.
• Queue is based on (FIFO) First in First Out Concept that means the node i.e. added
first is processed first.
• Here Enqueue is Insert Operation.
• Dequeue is nothing but Delete Operation.

Representation Of Queue In Memory


 The Queue is represented by a Linear array “Q” and two pointer variable FRONT
and REAR.
 FRONT gives the location of element to be deleted and REAR gives the location
after which the element will be inserted.
 The deletion will be done by setting

Front = Front + 1
 The insertion will be done by setting Rear = Rear + 1
QUEUE
• Queue is a linear data structure or sequential data structure where insertion take
place at one end and deletion take place at the other end.
• The insertion end of Queue is called rear end and deletion end is called front end.
• Queue is based on (FIFO) First in First Out Concept that means the node i.e. added
first is processed first.
• Here Enqueue is Insert Operation.
• Dequeue is nothing but Delete Operation.

Representation Of Queue In Memory


 The Queue is represented by a Linear array “Q” and two pointer variable FRONT
and REAR.
 FRONT gives the location of element to be deleted and REAR gives the location
after which the element will be inserted.
 The deletion will be done by setting

Front = Front + 1
 The insertion will be done by setting Rear = Rear + 1
Rear = Rear +1
3. Q [Rear] = ITEM
4. Exit
DELETION IN QUEUE(Dequeue)
Algorithm:
Delete (Q, ITEM, FRONT, REAR) This procedure remove element from queue Q.
1. If Front = Rear = NULL

Print ‘Underflow’ and Exit.


2. ITEM = Q (FRONT)
3. If Front = Rear

Front = NULL
Rear = NULL
else
Front = Front + 1
4. Exit
CIRCULAR QUEUE
 Let we have a queue that contain ‘n’ elements in which Q[1] comes after Q[n].
 When this technic is used to construct a queue then the queue is called circular
queue.
 In Circular queue when REAR is ‘n’ and any element is inserted then REAR will set
as 1.
 Similarly when the front is n and any element is deleted then front will be 1.
INSERTION ALGORITHM OF CIRCULAR QUEUE
Insert (Q, N, FRONT, REAR, ITEM) This procedure inserts an element ITEM into the
circular queue Q.
1. If Front = 1 and Rear = N

then print ‘Overflow’ and Exit.


2. If front = NULL
then Front = 1 and Rear = 1
else if Rear = N then
set Rear = 1
else
set Rear = Rear+1
(End of if Str.)
3. Set Q [Rear] = ITEM (Insert a new element)
4. Exit
DELETION ALGORITHM OF CIRCULAR QUEUE
Delete (Q, N, ITEM, FRONT, REAR) This procedure delete an element from a circular
queue.
1. If Front = NULL then write Underflow and Return.
2. Set ITEM = Q [FRONT]
3. If Front = Rear

Then Front = NULL and Rear = NULL


Else if Front = N then
Set Front = 1 else Front = Front+1 [End of if str.]
4. Return

PRIORITY QUEUE
 If is a type of queue in which each element has been assigned a priority such that
the order in which the elements are processed according to the elements are
processed according to the following rule
I. This element of high priority is processed first.
II. The element having same priority is processed according to the order in which
they are inserted.
 The lower ranked no. enjoy high priority.
MODULE 3
PROGRAMMING WITH LINKED LIST

Linked List is a collection of data elements called as nodes.


The node has 2 parts
 Info is the data part
 Next i.e. the address part that means it points to the next node.
If linked list adjacency between the elements are maintained by means of links or
pointers.
A link or pointer actually the address of the next node.
last node of the list contain ‘\0’ NULL which shows the end of the list.
The linked list contain another pointer variable ‘Start’ which contain the address the
first node.
Linked List is of 4 types
 Single Linked List
 Double Linked List
 Circular Linked List
 Header Linked List

Representation of Linked List in Memory


 Linked List can be represented in memory by means 2 linear arrays i.e. Data or
info and Link or address.

 They are designed such that info[K] contains the Kth element and Link[K] contains
the next pointer field i.e. the address of the Kth element in the list.
 The end of the List is indicated by NULL pointer i.e. the pointer field of the last
element will be NULLorZero
Start = 4
info [4] = N Link [4] = 3
info [3] = T Link [3] = 6
info [6] = E Link [6] = 2
info [2] = F Link [2] = 0 i.e. the null value
So the list has ended .
Representation of a node in a Linked List
Struct Link
{
int data ;
Struct Link * add ;
};

SINGLE LINKED LIST


A Single Linked List is also called as one-way list. It is a linear collection of data
elements called nodes, where the linear order is given by means of pointers.
Each node is divided into 2 parts.
I. Information
II. Pointer to next node.
OPERATION ON SINGLE LINKED LIST
1.Traversal
Algorithm:
Display (Start) This algorithm traverse the list starting from the 1st node to the end
of the list.
Step-1 : “Start” holds the address of the first node.
Step-2 : Set Ptr = Start [Initializes pointer Ptr]
Step-3 : Repeat Step 4 to 5, While Ptr ≠ NULL
Step-4 : Process info[Ptr] [apply Process to info(Ptr)]
Step-5 : Set Ptr = next[Ptr] [move Print to next node]
[End of loop]
Step-6 : Exit

2.Insertion
The insertion operation is used to add an element in an existing Linked List. There is
various positions where node can be inserted.
 Insert at the beginning
 Insert at end
 Insert at specific location.

Insert At The Beginning


Suppose the new mode whose information field contains 20 is inserted as the first
node.
Algorithm:
This algorithm is used to insert a node at the beginning of the Linked List. Start
holds the address of the first node.
Step-1 : Create a new node named as P.
Step-2 : If P == NULL then print “Out of memory space” and exit.

Step-3 : Set info [P] = 𝑥 (copies a new data into a new node)
Step-4 : Set next [P] = Start (new node now points to original first node)
Step-5 : Set Start = P
Step-6 : Exit
Insert At The End
To insert a node at the end of the list, we need to traverse the List and advance the
pointer until the last node is reached.
Suppose the new node whose information field contains 77 is inserted at the last
node
Algorithm:
This algorithm is used to insert a node at the end of the linked list. ‘Start’ holds the
address of the first node.
Step-1 : Create a new node named as P.
Step-2 : If P = NULL then print “Out of memory space” and Exit.
Step-3 : Set info [P] = 𝑥 (copies a new data into a new node)
Step-4 : Set next [P] = NULL
Step-5 : Set Ptr = Start
Step-6 : Repeat Step-7 while Ptr ≠ NULL
Step-7 : Set temp = Ptr
Ptr = next [Ptr] (End of step-6 loop)
Step-8 : Set next [temp] = P
Step-9 : Exit
Insert At Any Specific Location
To insert a new node at any specific location we scan the List from the beginning
and move up to the desired node where we want to insert a new node.
In the below fig. Whose information field contain 88 is inserted at 3rd location.
Algorithm:
‘Start’ holds the address of the 1st node.
Step-1 : Set Ptr = Start
Step-2 : Create a new node named as P.
Step-3 : If P = NULL then write ‘Out of memory’ and Exit.

Step-4 : Set info [P] = 𝑥 (copies a new data into a new node)
Step-5 : Set next [P] = NULL

Step-6 : Read Loc Step-7 : Set i = 1


Step-8 : Repeat steps 9 to 11 while Ptr ≠ NULL and i < Loc
Step-9 : Set temp = Ptr.
Step-10 : Set Ptr = next [Ptr]
Step-11 : Set i = i + 1
[End of step-7 loop]
Step-12 : Set next [temp] = P
Step-13 : Set next [P] = Ptr
Step-14 : Exit
3. Deletion
The deletion operation s used to delete an element from a single linked list. There
are various position where node can be deleted.
Delete the 1st Node
Algorithm:
Start holds the address of the 1st node.
Step-1 : Set temp = Start
Step-2 : If Start = NULL then write ‘UNDERFLOW’ & Exit.
Step-3 : Set Start = next[Start]
Step-4 : Free the space associated with temp.
Step-5 : Exit
Delete the last node
Algorithm:
Start holds the address of the 1st node.
Step-1 : Set Ptr = Start Step-2 : Set temp = Start
Step-3 : If Ptr = NULL then write ‘UNDERFLOW’ & Exit. Step-4 : Repeat Step-5 and 6
While next[Ptr] ≠ NULL Step-5 : Set temp = Ptr
Step-6 : Set Ptr = next[Ptr] (End of step 4 loop)
Step-7 : Set next[temp] = NULL
Step-8 : Free the space associated with Ptr.
Step-9 : Exit
Delete the node at any specific location

Algorithm:
Start holds the address of the 1st node.
Step-1 : Set Ptr = Start
Step-2 : Set temp = Start
Step-3 : If Ptr = NULL then write ‘UNDERFLOW’ and Exit.
Step-4 : Set i = 1
Step-5 : Read Loc
Step-6 : Repeat Step-7 to 9 while Ptr ≠ NULL and i < Loc
Step-7 : Set temp = Ptr
Step-8 : Set Ptr = next[Ptr]
Step-9 : Set i = i+1
(End of Step 6 loop)
Step-10 : Set next[temp] = next[Ptr]
Step-11 : Free the space associated with Ptr.
Step-12 : Exit
4. SEARCHING
Searching means finding an element from a given list
Algorithm:
Start holds the address of the 1st node.
Step-1 : Set Ptr = Start
Step-2 : Set Loc = 1
Step-3 : Read element
Step-4 : Repeat Step-5 and 7 While Ptr ≠ NULL
Step-5 : If element = info[Ptr] then Write ‘Element found at position’, Loc and Exit.
Step-6 : Set Loc = Loc+1
Step-7 : Set Ptr = next[Ptr]
(End of step 4 loop)
Step-8 : Write ‘Element not found’
Step-9 : Exit

Garbage Collection
The operating system of a computer may periodically collect all the deleted space
on to the free storage list. Any technique which does these collections is called
garbage collection.
When we delete a particular note from an existing linked list or delete the linked list
the space occupied by it must be given back to the free pool. So that the memory
can be the used by some other program that needs memory space.
To the free pool is done.
The operating system will perform this operation whenever it finds the CPU idle or
whenever the programs are falling short of memory space. The OS scans through
the entire memory cell & marks those cells. That are being by some program then it
collects the entire cell which are not being used & add to the free pool. So that this
cells can be used by other programs. This process is called garbage collection. The
garbage collection is invisible to the programmer.

You might also like