Unit - 2
Unit - 2
UNIT-2
Topic : Singly Linked List
LINKED LIST
DEFINITION
• Linked list is the most commonly used data structure used to store similar type of
data in memory.
• The elements of a linked list are not stored in adjacent memory locations as in
arrays
• It is the linear collection of data elements, called nodes, where the linear order is
implemented by means of pointer.
• Each node contains two fields,
❑ Create
❑ Insertion
❑ Is Empty
❑ Is Last
❑ Find
❑ Find Previous
❑ Find Next
❑ Deletion
ROUTINE TO CREATE A LIST
LIST createlist()
{
LIST L;
L=(struct Node *)malloc(sizeof(struct Node));
if(L==NULL)
printf("fatal error");
else
{
L->data=-1;
L->Next=NULL;
}
return L;
}
INSERTION IN A LIST
Insertion can be done either at the beginning, middle or end of linked list.
✔ Insert at beginning
∙ Store data
✔ Insert at end
∙ Store data
Void DeleteList(List L)
{
Position P,Temp;
P = L Next;
L Next = NULL;
While(P!= NULL)
{
Temp = P Next;
Free(P);
P = Temp;
}
}
EXAMPLE
THANK YOU
21CSC201J
DATA STRUCTURES AND
ALGORITHMS
UNIT-2
Topic :Doubly Linked List
DOUBLY LINKED LIST
A doubly linked list (DLL) is a special type of linked list in which each node contains a
pointer to the previous node as well as the next node of the linked list.
Memory Representation
Prons and Cons
Advantages of Doubly Linked List over the singly linked list:
• A DLL can be traversed in both forward and backward directions.
• The delete operation in DLL is more efficient if a pointer to the node to be deleted is
given.
• We can quickly insert a new node before a given node.
• In a singly linked list, to delete a node, a pointer to the previous node is needed. To get
this previous node, sometimes the list is traversed. In DLL, we can get the previous
node using the previous pointer.
Disadvantages of Doubly Linked List over the singly linked list:
• Every node of DLL Requires extra space for a previous pointer. It is possible to
implement DLL with a single pointer though (See this and this).
• All operations require an extra pointer previous to be maintained. For example, in
insertion, we need to modify previous pointers together with the next pointers. For
example in the following functions for insertions at different positions, we need 1 or 2
extra steps to set the previous pointer.
Creating a Node in DLL
// Linked List Node
struct node {
int info;
struct node *prev, *next;
};
struct node* start = NULL;
Function to traverse the linked list
// Else print the Data
void traverse()
{ struct node* temp;
} }
}
Function to insert at the front of the linked list
void insertAtFront()
{
int data;
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("\nEnter number to be inserted: ");
scanf("%d", &data);
temp->info = data;
temp->prev = NULL;
// Pointer of temp will be assigned to start
temp->next = start;
start = temp;
}
Function to insert at the end of the linked list
void insertAtEnd()
{
// If start is NULL // Changes Links
int data;
if (start == NULL) { else {
struct node *temp, *trav; while (trav->next != NULL)
temp = (struct node*)malloc(sizeof(struct node)); trav = trav->next;
start = temp; temp->prev = trav;
temp->prev = NULL;
} trav->next = temp;
temp->next = NULL; }
printf("\nEnter number to be inserted: "); }
scanf("%d", &data);
temp->info = data;
temp->next = NULL;
trav = start;
Function to insert at any specified
void insertAtPosition()
position in the
else if
linked
(pos == 1)
list
{ insertAtFront();
int data, pos, i = 1; else {
struct node *temp, *newnode; printf("\nEnter number to be inserted: ");
newnode = malloc(sizeof(struct node)); scanf("%d", &data);
newnode->next = NULL; newnode->info = data;
newnode->prev = NULL; temp = start;
// Enter the position and data while (i < pos - 1) {
printf("\nEnter position : "); temp = temp->next;
scanf("%d", &pos); i++;
if (start == NULL) }
{ newnode->next = temp->next;
start = newnode; newnode->prev = temp;
newnode->prev = NULL; temp->next = newnode;
newnode->next = NULL; temp->next->prev = newnode;
} }
}
Function to insert at any specified
position in the linked list
Function to delete from the front of
the linked list
void deleteFirst()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
else {
temp = start;
start = start->next;
if (start != NULL)
start->prev = NULL;
free(temp);
}
}
Function to delete from the end of the linked list
void deleteEnd()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
temp = start;
while (temp->next != NULL)
temp = temp->next;
if (start->next == NULL)
start = NULL;
else {
temp->prev->next = NULL;
free(temp);
}
}
Function to delete from any specified
position from the linked list
void deletePosition() if (start != NULL)
{
{
int pos, i = 1; position = temp->next;
struct node *temp, *position; start->prev = NULL;
if (position->next != NULL)
temp = start; }
position->next->prev = temp;
if (start == NULL) free(position);
temp->next = position->next;
printf("\nList is empty\n"); return;
else { }
printf("\nEnter position : ");
while (i < pos - 1) free(position);
scanf("%d", &pos); }
if (pos == 1) {
{
temp = temp->next; }
deleteFirst();
i++;
}
Applications of DLL
It is used in the navigation systems where
front and back navigation is required.
It is used by the browser to implement
backward and forward navigation of visited
web pages that is a back and forward
button.
It is also used to represent a classic game
deck of cards.
Applications of List Data Structure
Applications of List Data Structure
1. Sparse Matrix
2. Polynomial
3. Joseph Problem
1. Sparse Matrix
• a matrix can be defined with a 2-dimensional array
• Any array with 'm' columns and 'n' rows represent a m
X n matrix.
• There may be a situation in which a matrix contains
more number of ZERO values than NON-ZERO values.
Such matrix is known as sparse matrix.
Representation of Sparse Matrix
•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.
Representation of Sparse Matrix
contd.,
• A sparse matrix can be effectively represented
by using TWO representations, those are as
follows...
– Triplet Representation (Array Representation)
– Linked Representation
Triplet Representation of Sparse Matrix
• In this representation, only non-zero values along with their row and
column index values are considered. (Triplet: Row, Column, Value)
• In this representation, the 0th row stores the total number of rows,
total number of columns and the total number of non-zero values in
the sparse matrix.
• Example: consider a matrix of size 5 X 6 containing 6 number of
non-zero values. This matrix can be represented as shown in the
image...
Triplet Representation of Sparse
Matrix
Triplet Representation of Sparse Matrix (Using Array)
int main() // Making of new matrix
{ int k = 0;
// Assume 4x5 sparse matrix for (int i = 0; i < 4; i++)
int sparseMatrix[4][5] = for (int j = 0; j < 5; j++)
{ if (sparseMatrix[i][j] != 0)
{0 , 0 , 3 , 0 , 4 }, {
{0 , 0 , 5 , 7 , 0 }, compactMatrix[0][k] = i;
{0 , 0 , 0 , 0 , 0 }, compactMatrix[1][k] = j;
{0 , 2 , 6 , 0 , 0 } compactMatrix[2][k] = sparseMatrix[i][j];
}; k++;
}
int size = 0; for (int i=0; i<3; i++)
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) for (int j=0; j<size; j++)
if (sparseMatrix[i][j] != 0)
printf("%d ", compactMatrix[i][j]);
size++;
printf("\n");
// number of columns in compactMatrix (size) must
be }
// equal to number of non - zero elements in return 0;
// sparseMatrix }
int compactMatrix[3][size];
Linked List Representation of Sparse
Matrix
• In linked list, each node has four fields. These
four fields are defined 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)
– Next node: Address of the next node
Linked List Representation of Sparse
Matrix
Sparse Matrix Operations
• Transpose of a sparse matrix.
• What is the transpose of a matrix?
Note:
The max.size of the resultant structure will
be = no. of non-zero elements in (Matrix A
+ Matrix B) , if we don’t have any common
entries in both the tables A & B.
Sparse Matrix Operations - Multiplication
Sparse Matrix Operations - Multiplication
Sparse Matrix Operations - Multiplication
Sparse Matrix Operations - Multiplication
Sparse Matrix Operations - Multiplication
Sparse Matrix Operations - Multiplication
2. Polynomial Arithmetic using Linked List
• 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 of Polynomial.
UNIT-2
Topic : Circular linked list
Circular Linked List
Circular linked list
• The pointer from the last element in the list points back
to the first element.
head
A B C
Circular Linked List
• A circular linked list is basically a linear linked list that may be single- or double-linked.
• The only difference is that there is no any NULL value terminating the list.
• In fact in the list every node points to the next node and last node points to the first node, thus
forming a circle. Since it forms a circle with no end to stop it is called as circular linked list.
• In circular linked list there can be no starting or ending node, whole node can be traversed from any
node.
• In order to traverse the circular linked list, only once we need to traverse entire list until the starting
node is not traversed again.
• A circular linked list can be implemented using both singly linked list and doubly linked list.
Circular Linked List
Basic structure of singly circular linked list:
• Insert a node at any position of the list and delete from the beginning of the list.
• insert_position(data,position);
• delete_front();
UNIT-2
Topic : Implementation of List ADT-
Array, Cursor based & linked
Implementing an ADT
What happens if you want to insert an item at a specified position in an existing array?
1. Write over the current contents at the given index (which might not be appropriate), or
2. The item originally at the given index must be moved up one position, and all the items after
that index shuffled up.
Removal from Arrays
What happens if you want to remove an item from a specified position in an existing array?
1. Leave gaps in the array, i.e. indices that contain no elements, which in practice, means that
the array element has to be given a special value to indicate that it is “empty”, or
2. All the items after the (removal items) index must be shuffled down
Implementation of List ADT using Linked List
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct Node
{ int data;
struct Node *Next;
};
typedef struct Node *PtrToNode;
typedef PtrToNode LIST;
typedef PtrToNode POSITION;
int IsEmpty(LIST L)
{
return L->Next==NULL;
}
Title
Title
Title
List Implemented Using Array
• The List is an
• Ordered sequence of data items called elements
• A1, A2, A3, …,AN is a list of size N
• size of an empty list is 0
• Ai+1 succeeds Ai
• Ai-1 preceeds Ai
• Position of Ai is i
• First element is A1 called “head”
• Last element is AN called “tail”
Operations on List
• MakeEmpty
• PrintList
• Find
• FindKth
• Insert
• Delete
• Next
• Previous
List – An Example
• We’ll consider only few operations and not all operations on Lists
• Let us consider Insert
• There are two possibilities:
• Ordered List
• Unordered List
Insertion into an ordered list
Disadvantages of using Arrays
• Series of nodes
• not adjacent in memory
• contain the element and a pointer to a node containing its succesor
• Avoids the linear cost of insertion and deletion!
Advantages of using Linked Lists
UNIT-2
Topic : Introduction to List
List ADT - Operations
• Insertion
• Deletion
• Searching
• Sorting
• Merging
• Traversal
Insertion
• Insert the elements either at starting position
or at the middle or at last or anywhere in the
array.
• After inserting the element in the array, the
positions or index location is increased
Insertion
Deletion
• Input the size of the array arr[] using num, and then declare
the pos variable to define the position, and i represent the
counter value.