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

DSA - Unit2_Final_Updated

The document provides an overview of List Abstract Data Types (ADTs), detailing operations such as creation, insertion, searching, deletion, and display of elements. It discusses various implementations of List ADTs including array, cursor-based, and linked lists, along with their types (singly, doubly, circular) and applications in areas like sparse matrices and polynomial arithmetic. Additionally, it covers the advantages and disadvantages of linked lists, along with specific operations and methods for managing them.

Uploaded by

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

DSA - Unit2_Final_Updated

The document provides an overview of List Abstract Data Types (ADTs), detailing operations such as creation, insertion, searching, deletion, and display of elements. It discusses various implementations of List ADTs including array, cursor-based, and linked lists, along with their types (singly, doubly, circular) and applications in areas like sparse matrices and polynomial arithmetic. Additionally, it covers the advantages and disadvantages of linked lists, along with specific operations and methods for managing them.

Uploaded by

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

UNIT 2 – List Structure

Operations on List ADT – Create, Insert, Search,


Delete, Display elements; Implementation of List
ADT– Array, Cursor based and Linked; Types –
Singly, Doubly, Circular; Applications - Sparse
Matrix, Polynomial Arithmetic, Joseph Problem
Topics to be covered

• Operations on List ADT –


• Create, Insert, Search, Delete, Display elements
• Implementation of List ADT
• Array, Cursor based and Linked
• Types
• Singly, Doubly, Circular
• Applications
• Sparse Matrix, Polynomial Arithmetic, Joseph Problem

2
INTRODUCTION

3
Data Structure
• Data structure is a particular way of organizing,
storing and retrieving data, so that it can be used
efficiently.
• It is the structural representation of logical
relationships between elements of data.

4
Data Structure

5
Data Structure

6
Abstract Data Type
• ADT is a mathematical specification of the data, a list of
operations that can be carried out on that data.
• It includes the specification of what it does, but excludes the
specification of how it does. Operations on set ADT: Union,
Intersection, Size and Complement.
• The primary objective is to separate the implementation of
the abstract data types from their function.
• Three most common used abstract data types are Lists,
Stacks, and Queues.

7
Abstract Data Type
• Three most common used abstract data types are Lists,
Stacks, and Queues.
• ADT = Type + Functions+ Behavior of Each Function
• Benefits
• Code is easier to understand. Provides modularity and
reusability.
• Implementations of ADTs can be changed without requiring
changes to the program that uses the ADTs.

8
List ADT
• List is a linear collection of ordered elements.
• The general form of the list of size N is: A , A , …, A
0 1 N-1

• where A1 - First element


• A - Last element
N

• N - Size of the list


• If the element at position 'i' is Ai then its successor is Ai+1
and its predecessor is Ai-1.

9
List ADT
• Various operations performed on a List ADT
• Insert (X,5) - Insert the element X after the position 5.
• Delete (X) - The element X is deleted.
• Find (X) - Returns the position of X
• Next (i) - Returns the position of its successor
element i+1.
• Previous (i) - Returns the position of its predecessor
element i-1.
• PrintList - Displays the List contents.
• MakeEmpty - Makes the List empty.

10
List ADT
• Implementation of List ADT
• Array implementation
• Linked List implementation
• Cursor implementation

11
Array Implementation of List ADT
Array Implementation of List ADT
Array Implementation of List ADT

• Array Implementation of List ADT


Linked List

15
Linked List
• Linked list is a dynamic data structure which is an
ordered collection of homogeneous data elements
called nodes, in which each element contains two
parts: data or Info and one or more links.
• The data holds the application data to be processed.
The link contains (the pointer) the address of the
next element in the list.
Linked List
• A linked list is a linear collection of data elements.
These data elements are called nodes.
Linked List
• Why Linked List?
• Even though searching an array for an individual element can be very
efficient, array has some limitations. So arrays are generally not used
to implement Lists.
• Advantages of Linked List
• Linked list are dynamic data structures - The size is not fixed.
They can grow or shrink during the execution of a program.
• Efficient memory utilization - memory is not pre-allocated. Memory
is allocated, whenever it is required and it is de- allocated whenever it
is not needed. Data are stored in non-continuous memory blocks.
• Insertion and deletion of elements are easier and efficient.
Provides flexibility. No need to shift elements of a linked list to make
room for a new element or to delete an element.
• Disadvantages of Linked List
• More memory - Needs space for pointer (link field).
• Accessing arbitrary element is time consuming. Only sequential
search is supported not binary search.
Prepared By: L.Josephine Usha, AP/IT, SXCCE
Operations on Linked List
• Creation- This operation is used to create a linked list. Once a linked list is
created with one node, insertion operation can be used to add more elements in a
node.
• Insertion- This operation is used to insert a new node at any specified location in
the linked list. A new node may be inserted,
• At the beginning of the linked list,
• At the end of the linked list,
• At any specified position in between in a linked list.
• Deletion- This operation is used to delete an item (or node) from the linked list. A
node may be deleted from the,
• Beginning of a linked list,
• End of a linked list,
• Specified location of the linked list.
• Traversing - It is the process of going through all the nodes from one end to
another end of a linked list. In a singly linked list we can visit the nodes only from
left to right (forward traversing). But in doubly linked list forward and backward
traversing is possible.
• Searching- It is the process finding a specified node in a linked list.
• Concatenation- It is the process of appending the second list to the end of the
Linked List
• Types of linked list
• Singly linked list or Linear list or One-way list
• Doubly linked list or Two-way list
• Circular linked list
• Doubly circular linked list
Singly Linked List
• In singly linked list, each element (except the first one) has a
unique predecessor, and each element (except the last one)
has a unique successor.
• Each node contains two parts: data or Info and link.
• The data holds the application data to be processed. The link
contains the address of the next node in the list. That is, each
node has a single pointer to the next node. The last node
contains a NULL pointer indicating the end of the list.
Singly Linked List
• Sentinel Node
• It is also called as Header node or Dummy node.
• Advantages
• Sentinel node is used to solve the following problems
• First, there is no really obvious way to insert at the front of the
list from the definitions given.
• Second, deleting from the front of the list is a special case,
because it changes the start of the list; careless coding will lose
the list.
• A third problem concerns deletion in general. Although the pointer
moves above are simple, the deletion algorithm requires us to
keep track of the cell before the one that we want to delete.
• Disadvantages
• It consumes extra space.
Singly Linked List
• Insertion
• Creating a new node from empty List
Singly Linked List
• Insertion
• Inserting a node to the front of list
Singly Linked List
• Insertion
• Inserting a node in the middle
Singly Linked List
• Insertion
• Inserting a node to the end of list.
Singly Linked List
• Deletion
• Deleting a node to the front of list
Singly Linked List
• Deletion
• Deleting the middle node
Singly Linked List
• Deletion
• Deleting the last node
Singly Linked List

• Singly linked list implementation


Singly Linked List
• Singly linked list implementation
Singly Linked List
• Singly linked list implementation
Singly Linked List

• Singly linked list implementation


Singly Linked List
• Singly linked list implementation
Singly Linked List
• Singly linked list implementation
Singly Linked List
• Insertion Insert at Beginning
void Insert_beg (int X)
• Inserting a node to the
{
front of list
position NewNode;
NewNode = malloc (sizeof(struct Node));
if(NewNode != NULL)
{
NewNode->data = X;
NewNode->next = L->Next;
L->next = NewNode;
}
}
Singly Linked List
Insertion at Middle
• Insertion /* Insert element X after position P */ void
• Inserting a node in the Insert_mid (int X, position P)
middle {
position NewNode;
NewNode = malloc (sizeof(struct Node));
if(NewNode != NULL)
{
NewNode->data = X;
NewNode->next = P->next;
P->next = NewNode;
}
}
Singly Linked List
• Insertion Insert at Last
• Inserting a node to the end void Insert_last (int X)
of list {
position NewNode, P;
NewNode = malloc (sizeof(struct Node));
if(NewNode != NULL)
{
while(P->next!=NULL)
P = P->next;
NewNode->data = X;
NewNode->next = NULL;
P->next = NewNode;
}
Singly Linked List
Delete at Beginning
• Deletion void Delete_beg ()
• Deleting a node to the {
front of list position TempCell;
if(head->next!=NULL)
{
TempCell = head->next;
head->next = TempCell ->next;
free(TempCell);
}
}
Singly Linked List
• Deletion Delete at Middle Routine
• Deleting the middle node void Delete (int X)
{
position P, TempCell;
P = FindPrevious(X);
TempCell = P->next;
P->Next = TempCell ->Next; free(TempCell);
}
Singly Linked List
Delete at Last
• Deletion
void Delete_last ()
• Deleting the last node {

position TempCell,P;
while(P->next->next!=NULL)
P = P->next;
TempCell = P->next;
P->next = NULL;
free(TempCell);
}
Circular Linked List
• Definition
• A circular linked list is one, which has no beginning and no
end. Circular linked list is a list in which every node has a
successor; the "last" element is succeeded by the "first"
element. We can start at any node in the list and traverse
the entire list.
Circular Linked List
• Why circular linked list?
• With a singly linked list structure, given a pointer to a node anywhere in
the list, we can access all the nodes that follow but none of the nodes that
precede it. We must always have a pointer to the beginning of the list to
be able to access all the nodes in the list. In a circular linked list, every
node is accessible from a given node.
• In deletion of singly linked list, to find the predecessor requires that a
search be carried out by chaining through the nodes from the first node of
the list. But this requirement does not exist for a circular list, since the
search for the predecessor of node X can be initiated from X itself.
• Concatenation and splitting becomes more efficient.
Circular Linked List
• Disadvantages
• The circular linked list requires extra care to detect
the end of the list.
• It may be possible to get into an infinite loop. So it
needs a header node to indicate the start or end of
the list.
OPERATIONS ON CIRCULARLY LINKED LIST

•Insertion
•Deletion
•Display

Circular linked list – Creation

temp=head;
temp->next = new;
new -> next = head;
Insertion in a Circular Linked List

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
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 isEmpty (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 the End of the list
• 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)
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).
Inserting At Specific location in the list (After a Node)
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 9 - If temp is not last node then set newNode → next = temp → next

and temp → next = newNode.


Circular Linked List
Deletion
Operation
•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
• 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
• 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
• 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)
DELETING A SPECIFIC NODE FROM THE LIST
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 11- 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)).
Circular Linked List - Deletion Operation
•//delete first item //mark next to first link as first

•struct node * deleteFirst() { head = head->next;

//return the deleted link


•//save reference to first
link
return tempLink;
}
•struct node *tempLink =
head; if(head->next == head){
•head = NULL;
return tempLink;
Deleting first node from Singly Circular Linked List
• Given a Circular Linked List. The task is to write programs to delete nodes from this list
present at:

• First position.
• Last Position.
• At any given position i.
Deleting the last node of the Circular Linked List
Deleting nodes at given index in the Circular
linked list
Doubly Linked List
• Doubly linked list is a linked list in which each node is
linked to both its successor and its predecessor. In a
doubly linked list, the nodes are linked in both
directions.
• Each node of a doubly linked list contains three parts:
• Info: the data stored in the node
• Next/FLink: the pointer to the following node.
• Back/BLink: the pointer to the preceding node
Doubly Linked List
Doubly Linked List
• Why doubly linked list?
• In singly linked list, it is difficult to perform traversing the list
in reverse.
• To delete a node, we need find its predecessor of that node.
• Advantages
• Traversing in reverse is possible.
• Deletion operation is easier, since it has pointers to its
predecessor and successor.
• Finding the predecessor and successor of a node is easier.

Prepared By: L.Josephine Usha, AP/IT, SXCCE


Doubly Linked List
• Disadvantages
• A doubly linked list needs more operations while
inserting or deleting and it needs more space (to store
the extra pointer).
• There are more pointers to keep track of in a doubly linked
list. For example, to insert a new node after a given node,
in a singly linked list, we need to change two pointers. The
same operation on a doubly linked list requires four
pointer changes.

Prepared By: L.Josephine Usha, AP/IT, SXCCE


Doubly Circular Linked List
• A circular linked list is one, which has no beginning and no end.
• A doubly circular linked list is a doubly linked list with circular structure in
which the last node points to the first node and the first node points to the
last node and there are two links between the nodes of the linked list.
• In doubly circular linked list, the left link of the leftmost node contains the
address of the rightmost node and the right link of the rightmost node
contains the address of the leftmost node.
• Why doubly circular linked list?
• The aim of considering doubly circular linked list is to simplify the insertion
and deletion operations performed on doubly linked list.
Doubly Linked List
Doubly Linked list -
Motivation
•Doubly linked lists are useful for playing video and sound files with “rewind” and
“instant replay”

•They are also useful for other linked data which require “rewind” and “fast
forward” of the data
Doubly Linked
Lists
• Doubly linked lists
•Each node points to not only successor but the
predecessor
•There are two NULL: at the first and
last nodes in the list
•Advantage: given a node, it is easy to visit its predecessor.
Convenient to traverse lists backwards
Address of next
inf
node
o
NUL 13 6 12 NUL
L L
Address of
previous
node

Las
Hea
Doubly-linked
lists

Previous pointer Data Next pointer


myDL
L

head NUL
a b c L
last

• Each node contains a value, a link to its successor (if any),


and a link to its predecessor (if any)
• The header points to the first node in the list and to the last
node in the list (or contains null links if the list is empty)
Operations - Doubly
Linked List
•Create a Node
•Insertion at beginning of a list
•Insertion at end of the list
•Insertion after a given position
•Delete a node from beginning
•Delete a node from end
•Delete a node from any location
Creating a Node
struct node
{
Struct node *previous; •info: the user's data
Int info; •next, previous: the address of the next
Struct node *next;
} and previous node in the list
void display(struct node *head)
{
Struct node *P;
If (head==NULL) .back
previous
{
info
printf(List is empty \n”); next
return;
}
P=head;
printf(“List is: \t”);
While(P!=NULL)
{ printf(“%d”, P-
>info);
P=P->next;
Insertion at
Beginning
Struct node *insertAtBeginning (Struct node *head, int data)
•Time Complexity –O(1)
{
Struct node *temp;
temp=(Struct node*)malloc(sizeof (Struct node));
temp->info=data;
temp->previous=NULL;
temp->next=head; //starts pointing to head of list
If(head)
head->previous=temp;
head=temp; Address of next
inf node
return o
} head; 13 6 12
1 NUL
2 L
7
Address
tem of
previous
p node
Las
Insertion at
end • Time Complexity – O(n)

struct node *insertAtEnd (struct node *head, int data)


{
struct node *temp, *P;
temp=(struct node*)malloc(sizeof (struct node));
temp->info=data;
P=head;
If(P)
{ while(P->next!=NULL)
P = P->next;
P->next=temp;
Temp->previous = P;
Temp-> next=NULL; inf
} else o
13 6 12
head=temp;
return 8
} head;
Las
Hea
Insertion at a given
position
Struct node *insertAtPostion(Struct node *head, int data, int item)
{ Struct node *temp, *P;
temp=(Struct node*)malloc(Sizeof(struct node)); temp->info=data;
P=head; While(P!=NULL)
{
If(P->info==item) P= P->next;
{ }
Printf(“%d not present in the list \n \n”,
temp->previous=P;
item);
Temp->next=P->next; return head;
P->next->previous=temp }
P->next=temp; Return head; • Time
} Complexit
y –O(n)
Hea 13 6 12
1 NUL
d 2 L
NUL
L
7

tem Las
Deleting a node from the list
Struct node *delete(Struct node *head, int data) Else
{ {
Struct node *temp; printf(“Element %d not found \n”, data);
If(head==NULL) return head;
{ }
printf(“List is empty”); }
return head;
}
If(head->next==NULL) Time Complexity – O(1)
{
If(head->info==data)
{
temp=head;
head=NULL;
free(temp);
return head;
} tem
p

Hea 13 NUL
d L

NUL
L
Deletion of first
{
node
Struct node *delete(Struct node *head, int data)
Struct node *temp;
If(head==NULL)
{ •Time Complexity – O(1)
printf(“List is empty”);
return head;
}
If(head->info==data)
{
temp=head;
head=head->next;
head->previous=NULL;
free(temp);
return head;
}
Deletion of a node in the
middle
temp=head->next;
While(temp->next!=NULL)
{
If(temp->info==data)
{
temp->previous->next=temp->next;
temp->next->previous=temp->previous;
free(temp);
return head;
}
temp=temp->next;
}
13 12 8
6

NULL
Deletion of a node
at end
int deleteFromEnd()
{
struct node *temp;
temp = last;
if(temp->previous==NULL)
{
free(temp);
head=NULL;
last=NULL;
return 0;
}
printf("\nData deleted from list is %d \n",last->data);
last=temp->previous;
last->next=NULL;
free(temp);
return 0;
}

13 6 12

8
NULL
Advantages and Disadvantages of Doubly Linked List

• Advantages:

1.We can traverse in both directions i.e. from starting to end and as well as from end to
starting.
2. It is easy to reverse the linked list.
3.If we are at a node, then we can go to any node. But in linear linked list, it is not
possible to reach the previous node.

Disadvantages:

1.It requires more space per space per node because one extra field is required for pointer
to previous node.
2. Insertion and deletion take more time than linear linked list because more pointer
operations are required than linear linked list.
Review Questions
1) How do you calculate the pointer difference in a memory efficient double linked list?
a) head xor tail b) pointer to previous node xor pointer to next node
c) pointer to next node - pointer to previous node
d) pointer to previous node - pointer to next node

2) What is the time complexity of inserting a node in a doubly linked list?


a) O(nlogn) b) O(logn) c) O(n) d) O(1)

3) Consider the following doubly linked list: head-1-2-3-4-5-tail


Node temp = new Node(6, head, head.next()); Node temp1 = new Node(0, tail.getPrev(), tail);
head.setNext(temp); temp.getNext().setPrev(temp); tail.setPrev(temp1);
temp1.getPrev().setNext(temp1);
a) head-0-1-2-3-4-5-6-tail b) head-1-2-3-4-5-6-tail
c) head-6-1-2-3-4-5-0-tail d) head-0-1-2-3-4-5-tail
Review Questions …
Contd.
4) What is a memory efficient double linked list?
a) Each node has only one pointer to traverse the list back and forth.
b) The list has breakpoints for faster traversal
c) An auxiliary singly linked list acts as a helper list to traverse through the doubly linked list
d) None of these

5) Which of the following is false about a doubly linked list?


a) We can navigate in both the directions
b) It requires more space than a singly linked list
c) The insertion and deletion of a node take a bit longer
d) Implementing a doubly linked list is easier than singly linked list
Exercis
es
• Sort the DLL in ascending order.
• Count the number of nodes in the given DLL.
• Reverse all nodes in doubly linked list
• Swap Kth node from beginning with Kth node from end in a Linked List
• Insert value in sorted way in a sorted doubly linked list
• Remove duplicates from an unsorted doubly linked list
• Count triplets in a sorted doubly linked list whose sum is equal to a
given value x
• Check if a doubly linked list of characters is palindrome or not
References
1. Seymour Lipschutz, Data Structures with C, McGraw Hill, 2014
2. Mark Allen Weiss, Data Structures and Algorithm Analysis in C, 2nd ed.,
Pearson Education, 2015
3. https://cse.iitkgp.ac.in/~palash/Courses/2020PDS/PDS2020.html
4. http://www.btechsmartclass.com/data_structures
5. https://www.geeksforgeeks.org/
Applications of List
Sparse Matrix
Sparse Matrix…

•The 2d array can be used to represent a sparse matrix in which there are
three rows named as:
• Row: It is an index of a row where a non-zero element is located.
•Column: It is an index of the column where a non-zero element is located.
•Value: The value of the non-zero ele
•Representing a sparse matrix by a 2D array leads to wastage of lots of
memory as zeroes in the matrix are of no use in most of the cases.
•So, instead of storing zeroes with non-zero elements, we only store non-
zero elements. T
•This means storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix…

• Harry Markowitz coined the term Sparse Matrix


• Sparse matrices can be useful for computing large-
scale applications that dense matrices cannot handle.
• One such application involves solving differential
equations
partial by using the finite element method.
Sparse matrix…
Sparse matrix…
Sparse Matrix Representation
Sparse Matrix Representation…
Sparse Matrix Representation…
Sparse Matrix Representation…
Sparse Matrix Representation…
Sparse Matrix Representation…
Sparse Matrix Representation…
Sparse Matrix Example
Matrix Transposition
Matrix Transposition…
Matrix Multiplication
Matrix Multiplication…
Multiplication of Two Sparse
Matrices
Multiplication of Two Sparse
Matrices…
Multiplication of Two Sparse
Matrices…
Multiplication of Two Sparse
Matrices…
Linked List

10
5
Application of Linked List

10
6
Applications of linked list in
computer science
•Implementation of stacks and queues
•Implementation of graphs : Adjacency list representation of graphs is
most popular which is uses linked list to store adjacent vertices.
•Dynamic memory allocation : We use linked list of free blocks.
•Maintaining directory of names
•Performing arithmetic operations on long integers
•Manipulation of polynomials by storing constants in the node of
linked list
•representing sparse matrices
10
7
Applications of linked list in
real world
• Image viewer – Previous and next images are linked, hence can be
accessed by next and previous button.
• Previous and next page in web browser – We can access previous and
next url searched in web browser by pressing back and next button
since, they are linked as linked list.
• Music Player – Songs in music player are linked to previous and next
song. you can play songs either from starting or ending of the list.

10
8
Polynomial Arithmetic using Linked List

10
9
•A polynomial p(x) is the expression in variable x which
is in the form (axn + bxn-1 + …. + jx+ k), where a, b, c
…., k fall in the category of real numbers and 'n' is non
negative integer, which is called the degree
polynomial.
of
•A polynomial can be thought of as an ordered list of
non zero terms. Each non zero term is a two-tuple
which holds two pieces of information:
•The exponent part
•The coefficient part

11
0
Adding two polynomials using
Linked List
Given two polynomial numbers represented by a linked list.
Write a function that add these lists means add the coefficients
who have same variable powers.

1st number = 5x2 + 4x1 + 2x0


2nd number = -5x1 + 5x0

11
1
1. Applications of Circular List -Joseph
Problem
2. Doubly Linked List
Josephus Circle using circular linked list

• There are n people standing in a circle waiting to be executed. The counting out begins at
some point in the circle and proceeds around the circle in a fixed direction. In each step, a
certain number of people are skipped and the next person is executed. The elimination
proceeds around the circle (which is becoming smaller and smaller as the executed people
are removed), until only the last person remains, who is given freedom. Given the total
number of persons n and a number m which indicates that m-1 persons are skipped and m-th
person is killed in circle. The task is to choose the place in the initial circle so that you are the
last one remaining and so survive.
Example
Josephus Problem - Snippet
int josephus(int m, node *head)
{ f->next=head->next;
node *f; //sequence in which nodes getting deleted
int
c=1; printf("%d->",head->data);
while(h head=f->next;
ead- }
>next! printf("\n");
=head)
printf("Winner is:%d\n",head-
{
>data); return;
c=1
}
;
whi
le(c
!
=m
)
Exercise
•Write a C program to implement the following operations using
Circular Linked List
•Insertion in all the positions like start , middle and end
•Deletion in all the positions like start , middle and end
•Display
Quiz
1. Find the concept which is right for the below condition.“Any node can be a starting point.
We can traverse the whole list by starting from any point. We just need to stop when the
first visited node is visited again”.
• Circular Linked List
• Singly Linked List
• Stack
• Queue

2. What is the right statement (condition) to check the last node in the circular linked list.
(Assume temp is initialized as temp=head)
• temp->next=NULL
• temp->next=head
• temp=NULL
• temp=head
Quiz
3. Find the code used to count the nodes in the circular linked list.
Cursor Based
Implementation
Methodology
Motivation
• Some programming languages doesn’t support pointers.
• But we need linked list representation to store data.
• Solution:
• Cursor implementation – Linked list implementation using arrays.
What is Cursor
List?
•A CursorList is an array version of a Linked List.
•It is an array of list nodes but instead of each node containing a
pointer to the next item in the linked list, each node element in the
array contains the index for the next node element.
Methodolo
gy
•Convert a linked list based implementation to an array
based implementation.
• Instead of pointers, array index could be used to keep track of node.
•Convert the node structures (collection of data and next pointer) to a
global array of structures.
•Need to find a way to perform dynamic memory allocation performed
using malloc and free functions.
Initializing Cursor
Space
•Cursor_space[list] =0;
Cursor implementation of linked lists -
Example

“-” in Element column represents empty cell.


“0” in Next column represents end of the
list.

• If L= 5, then L represents list (A, B, E)


• If M= 3, then M represents list (C, D, F)
• Empty list(Always starts from 0): 0->6-
>4
Methodology: 1. Cursor
Representation
Slot Element Next
Model
Cursor Model:
0 header 1
• Global array of structures
1 - 2
• Each structure has two members
2 - 3 1. Element
3 - 4 2. Next
• Figure 2.7.1 has 11 array of structures.
4 - 5
5 - 6
Initial configuration of cursor:
6 - 7
7 - 8 • It contains empty list with 0 as header.
8 - 9
• 0->1->2->3->4->5->6->7->8->9->10
9 - 10
10 - 0 • Node 10 is the last node of the list with next pointer to ‘ 0 ’.

Figure 2.7.1 Array representation of the linked list


Inserting an element in the
linked list
•Steps:
1. Allocate a node from the cursor model.
2. Place the value in the element field of the node
3. Adjust the next pointer.
Methodology: 1. Insert an element
in a list
Slot Element Next 1. To Allocate a node to store an element Slot Element Next
0 header 1 • Find the free space in the cursor
• Select the node pointed by the next field 0 header 3
1 - 3 of the 0th node. 1 10 0
2 header 0 • In the figure 2.7.2
2 header 1
3 - 4 0 -> next is 1 3 - 4
4 - 5 • Find the location of node in the list after
which the new element to be inserted 4 - 5
5 - 6 5 - 6
6 - 8 2. Place the element in the node
6 - 8
• 1->element = 10
7 header 0 7 header 0
8 - 9 3. Adjust the pointers 8 - 9
9 - 10 • 0->next=1->next
• 1->next=0 9 - 10
10 - 0 • 2->next=1 10 - 0

Updated List is 2->1


After inserting 20
and 30
Slot Element Next Slot Element Next Slot Element Next
0 header 3 0 header 4 0 header 5
1 10 0 1 10 3 1 10 3
2 header 1 2 header 1 2 header 1
3 - 4 Insert(20,L)
3 20 0 Insert(30,L)
3 20 4
4 - 5 4 - 5 4 30 0
5 - 6 5 - 6 5 - 6
6 - 8 6 - 8 6 - 8
7 header 0 7 header 0 7 header 0
8 - 9 8 - 9 8 - 9
9 - 10 9 - 10 9 - 10
10 - 0 10 - 0 10 - 0
Methodology: 2. Finding an element
from the list
•Start from the header of the list.
•Traverse the list by comparing the elements in each node
•(p->element == x)
•If matching element is found return the slot number else return not
found.
Methodology: 2. Finding an element
from the list
Slot Element Next Slot Element Next
0 header 5 0 header 5
1 10 3 1 10 No matc3h
2 header 1 2 header 1
find(20,L )
3 20 4 3 20 mat ch 4
4 30 0 4 30 0 Returns 3
5 - 6 5 - 6
6 - 8 6 - 8
7 header 0 7 header 0
8 - 9 8 - 9
9 - 10 9 - 10
10 - 0 10 - 0
Methodology: 2. Delete an element
from a list
•Find the address of the element to be deleted.
•Get the address of the previous element(p) of the deletion
element(q)
•Adjust the next element of the previous node.
•p->next = q->next
•Add the freed node to the empty list
•q->next=0->next
•0->next = q
Methodology: 2. Deleting a node
from the list
Slot Element Next Slot Element Next
0 header 5 0 header 3
1 10 3 1 10 4
2 header 1 2 header 1
3 20 4 Delet(20,L) 3 - 5
4 30 0 4 30 0
5 - 6 5 - 6
6 - 8 6 - 8
7 header 0 7 header 0
8 - 9 8 - 9
9 - 10 9 - 10
10 - 0 10 - 0
Cursor Based
Implementation
1. Convert the node structures (collection of
data and next pointer) to a global array of
structures.
Declarations for cursor implementation of linked lists

Struct Node index Element Next


{
0 20 4
ElementType Element;
Position Next;
};

struct Node CursorSpace[SpaceSize];


typedef NodePtr List;
typedef NodePtr Position;
2. Need to find a way to perform dynamic
memory allocation performed using
malloc and free functions.
CursorAlloc() CursorFree()
Position CursorAlloc( void ) void CursorFree( Position P)
{ {
Position P;
CursorSpace[P].Next=CursorSpace[0].Next;
CursorSpace[0].Next = P;
P = CursorSpace[0].Next;
CursorSpace[0].Next = CursorSpace[P].Next; }

return P;
}
Initializing Cursor
Space
•Cursor_space[list] =0;
Cursor implementation of linked lists -
Example

“-” in Element column represents empty cell.


“0” in Next column represents end of the
list.

• If L= 5, then L represents list (A, B, E)


• If M= 3, then M represents list (C, D, F)
• Empty list(Always starts from 0): 0->6-
>4
IsEmpty() and
IsLast()
/* Return true if L is empty */
int IsEmpty(List L)
{
return
CursorSpace[L].Next == 0;
}

/* Return true if P is the last


node in the linked list */
/* Parameter L is unused in
this implementation */

int IsLast(Position P, List L)


{
return
CursorSpace[P].Next == 0;
Insert
Routine
/* Insert (after legal position P) */
/* Header implementation assumed */
/* Parameter L is unused in this implementation */

void Insert( ElementType x, List L, Position P )


{
Position TmpCell;

TmpCell = CursorAlloc( )
if( TmpCell ==0 )
fatal_error("Out of
space!!!");

CursorSpace[TmpCell].Element = x;
CursorSpace[TmpCell]. Next = CursorSpace[P]. Next;
CursorSpace[P]. Next =TmpCell;
}
Find
Routine
/* Return Position of X in L; 0 if not found */
/* Uses a header node */

Position Find( ElementType x, List L)


{
Position P;

P = CursorSpace[L].Next;
while( P && CursorSpace[P].Element != x )
P = CursorSpace[P].Next;

return P;
}
Deletion
Routine
/* Delete first occurrence of x from a list */
/* Assume use of a header node */

void Delete( ElementType x, List L )


{
Position P, TmpCell;

P = FindPrevious( x, L );

if( !IsLast( P, L) ) /* x is found; delete it */


{
TmpCell = CursorSpace[P].Next;
CursorSpace[P].Next = CursorSpace[TmpCell].Next;
CursorFree( TmpCell );
}
}
Practice
Exercises
1. Find the 3rd node from the end of a linked list Slot Element Next
0 header 6
given in the following cursor representation.
1 24 3
2. Sort the element of the linked list . 2 21 1
3. Find the 1st largest element in the linked 3 12 4

list. 4 5 9
5 7 0
4. Find the first 3 smallest element from the 6 - 8
linked list. 7 header 2
5. Remove duplicates from the given linked 8 - 10
list. 9 15 5
10 - 0
Review
1.
Questions
Why we need cursor implementation-> Implement linked list in programming language that do not support pointers
2. The cursor implementation is . Linked list implementation using arrays.
3. How to create linked list using cursor implementation-> Global Arrays of structures
4. Default list in cursor implementation is called .
Free list 0
5. The header of the free list is at location .
Value at next field of 0
6. Node to allocate and released node always occur at .
7. Condition to find the last node of the list . if(cursor[p].next == 0)

8. Condition to check whether the list is empty or not . if(cursor[L].next


== 0)
9. Code to assign element to the node . cursor[p].Element = x
10. Code to set a node as last node of a list . cursor[p].next = 0

You might also like