Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views39 pages

DS Unit-2

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)
9 views39 pages

DS Unit-2

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/ 39

DATA STRUCTURE

UNIT-2
LINKED LIST

2.1 Linked List


2.2 Singly Linked List
2.3 Linked Stacks and Queues
2.4 Polynomial Addition
2.5 More on Linked Lists
2.6 Sparse Matrices
2.7 Doubly Linked List and Dynamic
2.8 Storage Management
2.9 Garbage Collection and Compaction.
2.1 LINKED LIST:
 The linked list is a linear data structure that contains a sequence of elements such that
each element links to its next element in the sequence. Each element in a linked list is
called "Node".
 Linked List can be defined as collection of objects called nodes that are randomly stored
in the memory.
 A node contains two fields i.e. data stored at that particular address and the pointer which
contains the address of the next node in the memory.
 The last node of the list contains pointer to the null.

Representation of Linked List:


Each node consists:
1. A data items
2. An address of another node

Linked List Implementations in Python:


# Linked list implementation in Python
class Node:
# Creating a node
def __init__(self, item):
self.item = item
self.next = None

class LinkedList:
def __init__(self):
self.head = None

if __name__ == '__main__':
linked_list = LinkedList()

# Assign item values


linked_list.head = Node(1)
second = Node(2)
third = Node(3)
# Connect nodes
linked_list.head.next = second
second.next = third

# Print the linked list item


while linked_list.head != None:
print(linked_list.head.item, end=" ")
linked_list.head = linked_list.head.next

Linked List Implementations in C:


// Linked list implementation in C

#include <stdio.h>
#include <stdlib.h>

// Creating a node
struct node {
int value;
struct node *next;
};

// print the linked list value


void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 1;
two->value = 2;
three->value = 3;

// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;

// printing node-value
head = one;
printLinkedlist(head);
}

Linked List Complexity:


Time Complexity:
Worst Average
case Case

Search O(n) O(n)

Insert O(1) O(1)

Deletion O(1) O(1)

Linked List Applications:


1. Dynamic memory allocation
2. Implemented in stack and queue
3. In undo functionality of softwares
4. Hash tables, Graphs

2.2 SINGLY LINKED LIST


Single linked list is a sequence of elements in which every element has link to its next element in
the sequence.

1. In any single linked list, the individual element is called as "Node".


2. Every "Node" contains two fields, data field, and the next field.
3. The data field is used to store actual value of the node and next field is used to store the
address of next node in the sequence.
Important Points to be Remembered:
 +In a single linked list, the address of the first node is always stored in a reference node
known as "front" (Sometimes it is also known as "head").
 Always next part (reference part) of the last node must be NULL.

Example:

Operations on Single Linked List:


The following operations are performed on a Single Linked List
1. Insertion
2. Deletion
3. Display

Before we implement actual operations, first we need to set up an empty list. First, perform the
following steps before implementing actual operations.

Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable function
calls in the main method to perform user selected operation.

Insertion:
In a single linked list, the insertion operation can be performed in three ways. They are as
follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list:
We can use the following steps to insert a new node at beginning of the single linked list…
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set newNode→next = NULL and head = newNode.
Step 4 - If it is Not Empty then, set newNode→next = head and head = newNode.

Inserting At End of the list:


We can use the following steps to insert a new node at end of the single linked list...
Step 1 - Create a newNode with given value and newNode → next as NULL.
Step 2 - Check whether list is Empty (head == NULL).
Step 3 - If it is Empty then, set head = newNode.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next is equal to NULL).
Step 6 - Set temp → next = newNode.

Inserting At Specific location in the list (After a Node):


We can use the following steps to insert a new node after a node in the single linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set newNode → next = NULL and head = newNode.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the node after which we
want to insert the newNode (until temp1 → data is equal to location, here location is the
node value after which we want to insert the newNode).
Step 6 - Every time check whether temp is reached to last node or not. If it is reached to
last node then display 'Given node is not found in the list!!! Insertion not possible!!!' and
terminate the function. Otherwise move the temp to next node.
Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next = newNode’.

Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as
follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node

Deleting from Beginning of the list:


We can use the following steps to delete a node from beginning of the single linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Check whether list is having only one node (temp → next == NULL)
Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list
conditions)
Step 6 - If it is FALSE then set head = temp → next, and delete temp.

Deleting from End of the list:


We can use the following steps to delete a node from end of the single linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 → next == NULL)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the
function. (Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node.
Repeat the same until it reaches to the last node in the list. (until temp1 → next ==
NULL)
Step 7 - Finally, Set temp2 → next = NULL and delete temp1.

Deleting a Specific Node from the list


We can use the following steps to delete a specific node from the single linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the
last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
Step 5 - If it is reached to the last node then display 'Given node not found in the list!
Deletion not possible!!!'. And terminate the function.
Step 6 - If it is reached to the exact node which we want to delete, then check whether list
is having only one node or not
Step 7 - If list has only one node and that is the node to be deleted, then set head = NULL
and delete temp1 (free(temp1)).
Step 8 - If list contains multiple nodes, then check whether temp1 is the first node in the
list (temp1 == head).
Step 9 - If temp1 is the first node then move the head to the next node (head = head →
next) and delete temp1.
Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 →
next == NULL).
Step 11 - If temp1 is last node then set temp2 → next = NULL and delete temp1
(free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 →
next and delete temp1 (free(temp1)).

Displaying a Single Linked List


We can use the following steps to display the elements of a single linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last
node
Step 5 - Finally display temp → data with arrow pointing to NULL (temp → data --->
NULL).

Python
class Node:
def __init__(self, data):
self.data = data
self.next = None

node1 = Node(3)
node2 = Node(5)
node3 = Node(13)
node4 = Node(2)

node1.next = node2
node2.next = node3
node3.next = node4

currentNode = node1
while currentNode:
print(currentNode.data, end=" -> ")
currentNode = currentNode.next
print("null")
Output:
3 -> 5 -> 13 -> 2 -> null

2.3 LINKED STACKS AND QUEUES


 A stack data structure can be implemented by using a linked list data structure.
 The stack implemented using linked list can work for an unlimited number of values.
 That means, stack implemented using linked list works for the variable size of data. So,
there is no need to fix the size at the beginning of the implementation.
 The Stack implemented using linked list can organize as many data values as we want.

In linked list implementation of a stack, every new element is inserted as 'top' element. That
means every newly inserted element is pointed by 'top'. Whenever we want to remove an element
from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its previous
node in the list. The next field of the first element must be always NULL.

Example:

In the above example, the last inserted node is 99 and the first inserted node is 25. The order of
elements inserted is 25, 32,50 and 99.

Stack is a linear data structure that follows the Last-In-First-Out (LIFO) order of operations. This
means the last element added to the stack will be the first one to be removed. There are different
ways using which we can implement stack data structure.

struct Node {
type data;
Node* next;
}

Stack Operations using Linked List:


To implement a stack using a linked list, we need to set the following things before
implementing actual operations.

Step 1 - Include all the header files which are used in the program. And declare all the
user defined functions.
Step 2 - Define a 'Node' structure with two members data and next.
Step 3 - Define a Node pointer 'top' and set it to NULL.
Step 4 - Implement the main method by displaying Menu with list of operations and
make suitable function calls in the main method.

Push Function:
 The push function will add a new element to the stack.
 As the pop function require the time and space complexity to be O(1), we will insert the
new element in the beginning of the linked list.
 In multiple push operations, the element at the head will be the element that is most
recently inserted.

We need to check for stack overflow (when we try to push into stack when it is already full).

Algorithm for Push Function:


Following is the algorithm for the push function:
1. Create a new node with the given data.
2. Insert the node before the head of the linked list.
3. Update the head of the linked list to the new node.

push(value) - Inserting an element into the Stack:


We can use the following steps to insert a new node into the stack...
Step 1 - Create a newNode with given value.
Step 2 - Check whether stack is Empty (top == NULL)
Step 3 - If it is Empty, then set newNode → next = NULL.
Step 4 - If it is Not Empty, then set newNode → next = top.
Step 5 - Finally, set top = newNode.

Pop Function:
 The pop function will remove the topmost element from the stack.
 First remove the most recently inserted element.
 In this implementation, the most recently inserted element will be present at the head of
the linked list.

We first need to check for the stack underflow (when we try to pop stack when it is already
empty).
Algorithm for Pop Function:
Following is the algorithm for the pop function:
1. Check if the stack is empty.
2. If not empty, store the top node in a temporary variable.
3. Update the head pointer to the next node.
4. Free the temporary node.

pop() - Deleting an Element from a Stack


We can use the following steps to delete a node from the stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and
terminate the function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top → next'.
Step 5 - Finally, delete 'temp'. (free(temp)).

display() - Displaying stack of elements


We can use the following steps to display the elements (nodes) of a stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until
temp reaches to the first node in the stack. (temp → next != NULL).
Step 5 - Finally! Display 'temp → data ---> NULL'.

Peek Function:
 The peek function will return the topmost element of the stack if the stack is not empty.
The topmost element means the element at the head.

Algorithm for Peek Function:


The following is the algorithm for peek function:
1. Check if the stack is empty.
2. If its empty, return -1.
3. Else return the head->data.

IsEmpty Function:
 The isEmpty function will check if the stack is empty or not. This function returns true if
the stack is empty otherwise, it returns false.

Algorithm of isEmpty Function:


The following is the algorithm for isEmpty function:
1. Check if the top pointer of the stack is NULL.
2. If NULL, return true, indicating the stack is empty.
3. Otherwise return false indicating the stack is not empty.

Implementation of Stack using Linked List | C Programming


#include<stdio.h>
#include<conio.h>

struct Node
{
int data;
struct Node *next;
}*top = NULL;

void push(int);
void pop();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}

Output:
QUEUE USING LINKED LIST:
 A queue data structure can be implemented using a linked list data structure.
 The queue which is implemented using a linked list can work for an unlimited number of
values.
 Queue using linked list can work for the variable size of data (No need to fix the size at
the beginning of the implementation).
 The Queue implemented using linked list can organize as many data values as we want.
 In linked list implementation of a queue, the last inserted node is always pointed by 'rear'
and the first node is always pointed by 'front'.

Example:
In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted node
is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50.

Operations:
To implement queue using linked list, we need to set the following things before implementing
actual operations.
Step 1 - Include all the header files which are used in the program. And declare all the
user defined functions.
Step 2 - Define a 'Node' structure with two members data and next.
Step 3 - Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4 - Implement the main method by displaying Menu of list of operations and make
suitable function calls in the main method to perform user selected operation.

enQueue(value) - Inserting an element into the Queue


We can use the following steps to insert a new node into the queue...
Step 1 - Create a newNode with given value and set 'newNode → next' to NULL.
Step 2 - Check whether queue is Empty (rear == NULL)
Step 3 - If it is Empty then, set front = newNode and rear = newNode.
Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.

deQueue() - Deleting an Element from Queue


We can use the following steps to delete a node from the queue...
Step 1 - Check whether queue is Empty (front == NULL).
Step 2 - If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4 - Then set 'front = front → next' and delete 'temp' (free(temp)).

display() - Displaying the elements of Queue


We can use the following steps to display the elements (nodes) of a queue...
Step 1 - Check whether queue is Empty (front == NULL).
Step 2 - If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
Step 5 - Finally! Display 'temp → data ---> NULL'.
Implementation of Queue Data structure using Linked List - C Programming
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

void insert(int);
void delete();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}

Output:
2.4 POLYNOMIAL ADDITION
A polynomial is an expression that contains more than two terms. A term is made up of
coefficient and exponent.

Example:
P(x) = 4x3+6x2+7x+9

Adding Polynomials:
 A polynomial may be represented using array or structure.
 A structure may be defined such that it contains two parts – one is the coefficient and
second is the corresponding exponent.

Polynomial Structure Declaration


struct polynomial{
int coefficient;
int exponent;
};

 Polynomials are algebraic expressions that consist of constants and variables of different
powers. Adding polynomials is a way of combining and summing up terms having the
same power.
 Adding polynomials is defined as the addition operation of polynomials. Polynomials are
algebraic expressions of different degrees. While adding polynomials we follow some
specific rules which makes it very simple to do the operation.

Rules of Adding Polynomials:


Look at the two important rules of adding polynomials given below:
Rule 1: The like terms are always combined and added. Unlike terms can never be added.
Rule 2: While adding the terms, the sign always remains the same.

Like Terms
Like terms are defined as algebraic terms which have the same variables along with the same
exponents.
For example, 2x, 7x, -2x, etc are all like terms.

Unlike Terms
Unlike terms are the algebraic terms which do not have the same variables along with the same
exponents.
For example, 2, 7x2, -2y2, etc are all unlike terms.

Adding Polynomials Steps:


We can add polynomials using different methods. Let us briefly discuss two different methods to
add polynomials along with their steps and examples shown below.

Adding Polynomials Horizontally


For adding polynomials horizontally, we place the given polynomials in a horizontal manner.

Step 1: Write the polynomials in a horizontal manner with an addition (+) sign between them.
Step 2: Combine the like terms together by clubbing them in parentheses by retaining the sign of
every term.
Step 3: Perform the calculations.

Example: Add the polynomials 5x2 + 3x - 2 and 3x2 - x + 4 horizontally.

Following the steps above,


Step 1: 5x2 + 3x - 2 + 3x2 - x + 4
Step 2: (5x2 + 3x2) + (3x - x) + (- 2 + 4)
Step 3: 8x2 + 2x + 2
Thus, the addition of polynomials 5x2 + 3x - 2 and 3x2 - x + 4 is equal to 8x2 + 2x + 2.

Adding Polynomials Vertically:


For adding polynomials vertically, we place the polynomials column-wise vertically. Hence,
it is known as the vertical method of adding polynomials. Let's understand the steps below to add
polynomials vertically.

Step 1: Write the polynomials in standard form.


Step 2: Place the polynomials in a vertical arrangement, with the like terms placed one above the
other in both the polynomials.
Step 3: If any power term is missing in any polynomial, we write a '0' as its coefficient to avoid
confusion in the column-wise arrangement.
Step 4: Perform the calculations by retaining the sign of the terms.

Example: Add the polynomials 2x2 + 3x + 2 and 3x2 - 5x -1 vertically.

The polynomials 2x2 + 3x + 2 and 3x2 - 5x -1 are written in standard form. Let's arrange them
vertically and perform the calculations as shown below.

Therefore, on adding 2x2 + 3x +2 and 3x2 - 5x -1 we get 5x2 - 2x + 1.

How to Add Two Polynomials?


To add two polynomials using structure, just add the coefficient parts of the polynomials having
same exponent.
Add Polynomial Function Declaration
addPolynomial(
struct polynomial p1[10],
struct polynomial p2[10],
int t1,
int t2,
struct polynomial p3[10]);

Polynomial Addition Algorithm


1. [Initialize segment variables]
[Initialize Counter] Set i=0,j=0,k=0

2. Repeat while i<t1 and j<t2


IF p1[i].expo=p2[j].expo, THEN
p3[i].coeff=p1[i].coeff+p2[i].coeff
p3[k].expo=p1[i].expo
[Increase counter] Set i=i+1,j=j+1,k=k+1
ELSE IF p1[i].expo > p2[j].expo, THEN
p3[k].coeff=p1[i].coeff
p3[k].expo=p1[i].expo
[Increase counter] Set i=i+1,k=k+1
ELSE
p3[k].coeff=p2[j].coeff
p3[k].expo=p2[j].expo
Set j=j+1,k=k+1
[End of If]
[End of loop]

3. Repeat while i<t1


p3[k].coeff=p1[i].coeff
p3[k].expo=p1[i].expo
Set i=i+1,k=k+1
[End of loop]
4. Repeat while j<t2
p3[k].coeff=p2[j].coeff
p3[k].expo=p2[j].expo
Set j=j+1,k=k+1
[End of loop]
5. Return k
6. EXIT
2.5 MORE ON LINKED LISTS
Circular Linked List:
 A circular linked list is a sequence of elements in which every element has a link to its
next element in the sequence and the last element has a link to the first element.
 In single linked list, every node points to its next node in the sequence and the last node
points NULL. But in circular linked list, every node points to its next node in the
sequence but the last node points to the first node in the list.
 That means circular linked list is similar to the single linked list except that the last node
points to the first node in the list.

Example:

Operations
In a circular linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display

Before we implement actual operations, first we need to setup empty list. First perform the
following steps before implementing actual operations.

Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable
function calls in the main method to perform user selected operation.

Insertion:
In a circular linked list, the insertion operation can be performed in three ways. They are as
follows...

Inserting At Beginning of the list


1. Inserting At End of the list
2. Inserting At Specific location in the list
3. Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the circular linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set head = newNode and newNode→next = head .
Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head'.
Step 5 - Keep moving the 'temp' to its next node until it reaches to the last node (until
'temp → next == head').
Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp → next = head'.

Inserting At End of the list:


We can use the following steps to insert a new node at end of the circular linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL).
Step 3 - If it is Empty then, set head = newNode and newNode → next = head.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next == head).
Step 6 - Set temp → next = newNode and newNode → next = head.

Inserting At Specific location in the list (After a Node):


We can use the following steps to insert a new node after a node in the circular linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set head = newNode and newNode → next = head.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the node after which we
want to insert the newNode (until temp1 → data is equal to location, here location is the
node value after which we want to insert the newNode).
Step 6 - Every time check whether temp is reached to the last node or not. If it is reached
to last node then display 'Given node is not found in the list!!! Insertion not possible!!!'
and terminate the function. Otherwise move the temp to next node.
Step 7 - If temp is reached to the exact node after which we want to insert the newNode
then check whether it is last node (temp → next == head).
Step 8 - If temp is last node then set temp → next = newNode and newNode → next =
head.
Step 8 - If temp is not last node then set newNode → next = temp → next and temp →
next = newNode.

Deletion
In a circular linked list, the deletion operation can be performed in three ways those are as
follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node

Deleting from Beginning of the list:


We can use the following steps to delete a node from beginning of the circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize both 'temp1' and 'temp2' with head.
Step 4 - Check whether list is having only one node (temp1 → next == head)
Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list
conditions)
Step 6 - If it is FALSE move the temp1 until it reaches to the last node. (until temp1 →
next == head )
Step 7 - Then set head = temp2 → next, temp1 → next = head and delete temp2.

Deleting from End of the list:


We can use the following steps to delete a node from end of the circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 → next == head)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from the
function. (Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node.
Repeat the same until temp1 reaches to the last node in the list. (until temp1 → next ==
head)
Step 7 - Set temp2 → next = head and delete temp1.

Deleting a Specific Node from the list:


We can use the following steps to delete a specific node from the circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and
initialize 'temp1' with head.
Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the
last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
Step 5 - If it is reached to the last node then display 'Given node not found in the list!
Deletion not possible!!!'. And terminate the function.
Step 6 - If it is reached to the exact node which we want to delete, then check whether list
is having only one node (temp1 → next == head)
Step 7 - If list has only one node and that is the node to be deleted then set head = NULL
and delete temp1 (free(temp1)).
Step 8 - If list contains multiple nodes then check whether temp1 is the first node in the
list (temp1 == head).
Step 9 - If temp1 is the first node then set temp2 = head and keep moving temp2 to its
next node until temp2 reaches to the last node. Then set head = head → next, temp2 →
next = head and delete temp1.
Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 →
next == head).
Step 1 1- If temp1 is last node then set temp2 → next = head and delete temp1
(free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 →
next and delete temp1 (free(temp1)).

Displaying a circular Linked List


We can use the following steps to display the elements of a circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last
node
Step 5 - Finally display temp → data with arrow pointing to head → data.

Example:
class Node:
def __init__(self, data):
self.data = data
self.next = None

node1 = Node(3)
node2 = Node(5)
node3 = Node(13)
node4 = Node(2)

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node1

currentNode = node1
startNode = node1
print(currentNode.data, end=" -> ")
currentNode = currentNode.next

while currentNode != startNode:


print(currentNode.data, end=" -> ")
currentNode = currentNode.next

print("...")

Output:
3 -> 5 -> 13 -> 2 -> …

2.6 SPARSE MATRICES


 Sparse matrix is a matrix which contains very few non-zero elements.
 A sparse matrix is defined as a 2-D matrix representing the total values of m x n and is
composed of n columns and m rows. A matrix is referred to as sparse if the majority of its
elements have a value of 0.

The use of a sparse matrix over a basic matrix is executed as

1. Storage: Since fewer non-zero elements exist than zeroes, fewer elements can be stored in
a given amount of memory.
2. Computing time: By logically creating a data structure that only traverses non-zero
components, computation time can be minimized.

Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation
2. Linked list representation

Method 1: Using Arrays:


2D array is used to represent a sparse matrix in which there are three rows named as
1. Row: Index of row, where non-zero element is located
2. Column: Index of column, where non-zero element is located
3. Value: Value of the non zero element located at index – (row,column)

Example:
sparseMatrix = [[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]]

# initialize size as 0
size = 0

for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
size += 1

# number of columns in compactMatrix(size) should


# be equal to number of non-zero elements in sparseMatrix
rows, cols = (3, size)
compactMatrix = [[0 for i in range(cols)] for j in range(rows)]

k=0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
compactMatrix[0][k] = i
compactMatrix[1][k] = j
compactMatrix[2][k] = sparseMatrix[i][j]
k += 1

for i in compactMatrix:
print(i)
Output:
001133
242312
345726

Method 2: Using Linked Lists


In linked list, each node has four fields. These four fields are defined as:
1. Row: Index of row, where non-zero element is located
2. Column: Index of column, where non-zero element is located
3. Value: Value of the non zero element located at index – (row,column)
4. Next node: Address of the next node.

Example:
#include<stdio.h>
#include<stdlib.h>

// Node to represent sparse matrix


struct Node
{
int value;
int row_position;
int column_postion;
struct Node *next;
};

// Function to create new node


void create_new_node(struct Node** start, int non_zero_element,
int row_index, int column_index )
{
struct Node *temp, *r;
temp = *start;
if (temp == NULL)
{
// Create new node dynamically
temp = (struct Node *) malloc (sizeof(struct Node));
temp->value = non_zero_element;
temp->row_position = row_index;
temp->column_postion = column_index;
temp->next = NULL;
*start = temp;

}
else
{
while (temp->next != NULL)
temp = temp->next;

// Create new node dynamically


r = (struct Node *) malloc (sizeof(struct Node));
r->value = non_zero_element;
r->row_position = row_index;
r->column_postion = column_index;
r->next = NULL;
temp->next = r;

}
}

// This function prints contents of linked list


// starting from start
void PrintList(struct Node* start)
{
struct Node *temp, *r, *s;
temp = r = s = start;

printf("row_position: ");
while(temp != NULL)
{

printf("%d ", temp->row_position);


temp = temp->next;
}
printf("\n");
printf("column_postion: ");
while(r != NULL)
{
printf("%d ", r->column_postion);
r = r->next;
}
printf("\n");
printf("Value: ");
while(s != NULL)
{
printf("%d ", s->value);
s = s->next;
}
printf("\n");
}

// Driver of the program


int main()
{
// Assume 4x5 sparse matrix
int sparseMatric[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

/* Start with the empty list */


struct Node* start = NULL;

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


for (int j = 0; j < 5; j++)

// Pass only those values which are non - zero


if (sparseMatric[i][j] != 0)
create_new_node(&start, sparseMatric[i][j], i, j);

PrintList(start);
return 0;
}

Output:
row_position:0 0 1 1 3 3
column_position:2 4 2 3 1 2
Value:3 4 5 7 2 6

2.7 DOUBLY LINKED LIST AND DYNAMIC


 Double linked list is a sequence of elements in which every element has links to its
previous element and next element in the sequence.
 In a double linked list, every node has a link to its previous node and next node. So, we
can traverse forward by using the next field and can traverse backward by using the
previous field.
 Every node in a double linked list contains three fields and they are shown in the
following figure…

Here, 'link1' field is used to store the address of the previous node in the sequence, 'link2' field is
used to store the address of the next node in the sequence and 'data' field is used to store the
actual value of that node.

Example:

Important Points to be Remembered:


1. In double linked list, the first node must be always pointed by head.
2. Always the previous field of the first node must be NULL.
3. Always the next field of the last node must be NULL.
S.NO OPERATION DESCRIPTION

1. Insertion at Beginning Adding the node into the linked list at beginning.

2. Insertion at End Adding the node into the linked list to the end.

3. Insertion after Adding the node into the linked list after the specified
specified Node node.

4. Deletion at Beginning Removing the node from beginning of the list

5. Deletion at End Removing the node from end of the list.

6. Deletion of the node Removing the node which is present just after the node
having given Data containing the given data.

7. Searching Comparing each node data with the item to be searched


and return the location of the item in the list if the item
found else return null.

8. Traversing Visiting each node of the list at least once in order to


perform some specific operation like searching, sorting,
display, etc.

Representation of Doubly Linked List in Data Structure:


In a data structure, a doubly linked list is represented using nodes that have three fields:
1. Data
2. A pointer to the next node (next)
3. A pointer to the previous node (prev).

Operations on Doubly Linked List:


1. Traversal in Doubly Linked List
2. Searching in Doubly Linked List
3. Finding Length of Doubly Linked List
Insertion in Doubly Linked List:
1. Insertion at the beginning of Doubly Linked List
2. Insertion at the end of the Doubly Linked List
3. Insertion at a specific position in Doubly Linked List
Deletion in Doubly Linked List:
1. Deletion of a node at the beginning of Doubly Linked List
2. Deletion of a node at the end of Doubly Linked List
3. Deletion of a node at a specific position in Doubly Linked List.

Traversal in Doubly Linked List:


To Traverse the doubly list, we can use the following steps:

a. Forward Traversal:
Initialize a pointer to the head of the linked list.
1. While the pointer is not null:
2. Visit the data at the current node.
3. Move the pointer to the next node.

b. Backward Traversal:
Initialize a pointer to the tail of the linked list.
1. While the pointer is not null:
2. Visit the data at the current node.
3. Move the pointer to the previous node.

Advantages of Doubly Linked List:


 Efficient traversal in both directions
 Easy insertion and deletion of nodes
 Can be used to implement a stack or queue

Disadvantages of Doubly Linked List:


 More complex than singly linked lists
 More memory overhead.

Example:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
node1 = Node(3)
node2 = Node(5)
node3 = Node(13)
node4 = Node(2)

node1.next = node2

node2.prev = node1
node2.next = node3
node3.prev = node2
node3.next = node4

node4.prev = node3

print("\nTraversing forward:")
currentNode = node1
while currentNode:
print(currentNode.data, end=" -> ")
currentNode = currentNode.next
print("null")

print("\nTraversing backward:")
currentNode = node4
while currentNode:
print(currentNode.data, end=" -> ")
currentNode = currentNode.prev
print("null")

Output:
Traversing forward:
3 -> 5 -> 13 -> 2 -> null
Traversing backward:
2 -> 13 -> 5 -> 3 -> null

2.8 STORAGE MANAGEMENT


Storage management in data structures involves the efficient organization, allocation, and
deallocation of memory to store data and ensure optimal performance of algorithms. Here are
key concepts and techniques related to storage management in data structures:

Memory Allocation:
 Static Allocation: Memory size is determined at compile time. Used in arrays where the
size is fixed.
 Dynamic Allocation: Memory size is determined at runtime. Used in data structures like
linked lists, trees, and graphs. Functions like malloc, calloc, realloc, and free in C/C++
manage dynamic memory.

Contiguous and Non-Contiguous Storage:


 Contiguous Storage: Data is stored in a single, continuous block of memory. Arrays are
a typical example. Efficient for indexing but may cause memory fragmentation.
 Non-Contiguous Storage: Data is stored in multiple, non-adjacent blocks of memory.
Linked lists and hash tables use this method, offering flexibility and efficient memory use
but with slower access times due to pointer traversal.

Garbage Collection:
 Automatic memory management technique used in languages like Java and Python to
reclaim memory occupied by objects that are no longer in use, preventing memory leaks.

Stack and Heap:


 Stack: Used for static memory allocation, local variables, and function call management.
Follows LIFO (Last In, First Out) principle.
 Heap: Used for dynamic memory allocation. Managed explicitly by the programmer or
through garbage collection.

Data Structure-Specific Management:


 Arrays: Fixed size, quick access via indexing, poor at insertions/deletions.
 Linked Lists: Dynamic size, efficient insertions/deletions, slow access times.
 Trees: Hierarchical storage, efficient for searching/sorting operations (e.g., binary search
trees).
 Graphs: Used for modeling relationships between pairs, with adjacency matrices
(contiguous) or adjacency lists (non-contiguous).

Memory Fragmentation:
 Internal Fragmentation: Occurs when allocated memory may have small unused
portions within it due to fixed-size memory blocks.
 External Fragmentation: Occurs when free memory is divided into small blocks and
scattered throughout, making it difficult to allocate contiguous blocks of memory.
Caching and Paging:
 Techniques used in memory management to improve access times.
 Caching stores frequently accessed data in faster memory.
 Paging divides memory into fixed-size pages to manage physical and virtual memory
efficiently.

Memory Management Algorithms:


 First-Fit: Allocates the first block of memory that is large enough.
 Best-Fit: Allocates the smallest block of memory that is large enough, which can lead to
fragmentation.
 Worst-Fit: Allocates the largest block of memory to leave big leftover chunks.

Strategies for Efficient Memory Management:


 Pooling: Reusing fixed-size blocks of memory for objects of the same size to reduce
overhead and fragmentation.
 Compaction: Moving allocated objects to one end of the memory to create a large
contiguous block of free memory.
 Copying: Moving all live objects to a new memory region and freeing the old region,
which helps in reducing fragmentation.

2.9 GARBAGE COLLECTION AND COMPACTION


 Garbage collection and compaction are essential processes in memory management for
data structures, especially in the context of programming languages that manage memory
automatically, such as Java, Python, and C#.

 Garbage collection (GC) is the process of automatically identifying and reclaiming


memory that is no longer in use by the program. This helps to prevent memory leaks and
other issues related to dynamic memory management.

Types of Garbage Collection


Mark-and-Sweep:
1. Mark Phase: The garbage collector traverses the object graph starting from root objects
(e.g., global variables, stack variables) and marks all reachable objects.
2. Sweep Phase: It then scans the heap for unmarked objects and reclaims their memory.

Copying:
1. This involves dividing the memory into two halves. Active objects are copied from one
half (from-space) to the other half (to-space), and memory from the from-space is
reclaimed all at once.
2. This method minimizes fragmentation and is often used in young generation (or nursery)
spaces in generational GC.

Reference Counting:
1. Each object has a counter that tracks the number of references to it. When the reference
count drops to zero, the object is immediately reclaimed.
2. This method can struggle with cyclic references.

Generational:
1. Memory is divided into generations based on object lifespan (e.g., young, old). Young
generation spaces are collected more frequently than old generations because most
objects die young.
2. Combines different garbage collection techniques for different generations.

Incremental (or Concurrent) Garbage Collection:


1. The garbage collector runs in small steps, interleaved with the program execution, to
avoid long pause times.

Tracing:
1. Includes variations like tri-color marking (white, grey, black) to incrementally mark and
sweep objects in cycles to minimize pause times.

Functions of Garbage Collection


 Allocation: Allocates memory for new objects.
 Marking: Marks all objects that are reachable from root objects.
 Sweeping: Reclaims memory occupied by unmarked objects.
 Compaction: Moves reachable objects together to reduce fragmentation (common in
copying collectors).
 Finalization: Calls finalizers or destructors for objects before reclaiming their memory, if
applicable.

COMPACTION:
 Compaction is the process of moving objects in memory to reduce fragmentation and
make more contiguous blocks of free memory available.
 This helps in efficient memory allocation and reduces the overhead associated with
fragmented memory spaces.

Types of Compactions:
Copying Collection:
1. As described above, this method copies live objects to a new space, thus compacting
memory in the process.
Mark-Compact Collection:
1. After marking live objects, this method shifts them towards one end of the heap, thus
compacting the memory.

Sliding Compaction:
1. Similar to mark-compact, but typically more sophisticated in how it tracks and moves
objects to minimize copying overhead.

Functions of Compaction:
 Live Object Identification: Identify which objects are live and need to be moved.
 Relocation: Calculate new positions for live objects.
 Update References: Update all pointers to the moved objects to their new addresses.
 Free Space Management: Consolidate free spaces into a contiguous block to allow
efficient allocation.

Example in Java (Garbage Collection)


Java uses a combination of garbage collection techniques in its HotSpot JVM:
Young Generation GC (typically uses copying collection):

public class Example {


public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
Object obj = new Object();
}
}
}
The young generation is collected using a copying collector (e.g., G1, Parallel, or Serial
collector).

Old Generation GC (uses mark-sweep-compact):


 When objects survive multiple young generation GCs, they are promoted to the old
generation, which is collected using a mark-sweep-compact approach.

Summary:
Garbage collection and compaction are vital processes in automatic memory management,
ensuring efficient use of memory and preventing memory-related issues. Different techniques
and algorithms are used based on the programming language and specific requirements of the
runtime environment.

******************************************************************************

You might also like