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

Unit - 2

unit

Uploaded by

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

Unit - 2

unit

Uploaded by

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

21CSC201J

DATA STRUCTURES AND


ALGORITHMS

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,

Data: It holds a element


Next: It stores a link to next node in the list
EXAMPLE – SINGLE LINKED LIST

The structure definition for a single linked list is implemented as follows


Struct node
{
int data;
struct node *next
};
STRUCTURE AND VARIABLES FOR THE
LIST
struct Node
{
int data;
struct Node *Next;
};
typedef struct Node *PtrToNode;
typedef PtrToNode LIST;
typedef PtrToNode POSITION;
OPERATIONS ON SINGLY LINKED
LIST
The following are the possible operations on a Singly Linked List

❑ 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

∙ Allocate memory for new node

∙ Store data

∙ Change next of new node to point to head

∙ Change head to point to recently created node

✔ Insert at end

∙ Allocate memory for new node

∙ Store data

∙ Traverse to last node

∙ Change next of last node to recently created node

✔ Insert at middle (Or in a given Position)

∙ Allocate memory and store data for new node

∙ Traverse to node just before the required position of new node

∙ Change next pointers to include new node in between


ROUTINE TO INSERT IN A GIVEN
POSITION

void insert (int X ,int L ,position P)


{
position Newnode;
Newnode =(struct Node *)malloc(sizeof(struct Node)) ;
if (Newnode ==NULL)
printf(“Fatal Error”);
else
{
Newnode ->Element =X;
Newnode ->Next =P ->Next;
P ->Next =Newnode;
}
}
EXAMPLE - INSERTION
ROUTINE - IS EMPTY
ROUTINE – LAST POSITION
ROUTINE - FIND
Find operation is used to find the position of the given element.

position Find (int X, List L)


{
position P;
P = L -> Next;
While (p!=NULL && P -> Element !=X)
P =P -> Next;
return P;
}
ROUTINE – FIND PREVIOUS
Find Previous operation is used to find the previous position of the given element.

Position FindPrevious (int X, List L)


{
position P;
P=L;
While (P -> Next != Null && P -> Next -> Element !=X)
P=P -> Next;
return p;
}
ROUTINE – FIND NEXT
Find Next operation is used to find the next position of the given element.

Position FindNext (int X, List L)


{
P=L -> Next;
While (P -> Next != Null && P -> Element !=X)
P=P -> Next;
return P -> Next;
}
ROUTINE - DELETION
You can delete either from beginning, end or from a particular position.
•Delete from beginning
❑ Point head to the second node
head = head->next;
•Delete from end
❑ Traverse to second last element
❑ Change its next pointer to null
•Delete from middle
❑ Traverse to element before the element to be deleted
❑ Change next pointers to exclude the node from the chain
ROUTINE TO DELETE AN ELEMENT FROM
THE LIST
Void Delete ( int X, List L)
{
Position P, Temp;
P = Findprevious (X,L);
If(!IsLast(P,L))
{
Temp = P Next;
P Next = Temp Next;
Free (Temp);
}
}
ROUTINE TO DELETE A LIST
❑ It is used to delete the whole list and make it as empty list.

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;

// List is empty temp = start;

if (start == NULL) { while (temp != NULL) {

printf("\nList is empty\n"); printf("Data = %d\n", temp->info);

return; temp = temp->next;

} }
}
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?

row col value row col value


a[0] 6 6 8 b[0] 6 6 8
[1] 0 0 15 [1] 0 0 15
[2] 0 3 22 [2] 0 4 91
transpose
[3] 0 5 -15 [3] 1 1 11
[4] 1 1 11 [4] 2 1 3
[5] 1 2 3 [5] 2 5 28
[6] 2 3 -6 [6] 3 0 22
[7] 4 0 91 [7] 3 2 -6
[8] 5 2 28 [8] 5 0 -15
Sparse Matrix Operations -Transpose
(1) for each row i
take element <i, j, value> and store it
in element <j, i, value> of the transpose.

difficulty: where to put <j, i, value>?


(0, 0, 15) ====> (0, 0, 15)
(0, 3, 22) ====> (3, 0, 22)
(0, 5, -15) ====> (5, 0, -15)
(1, 1, 11) ====> (1, 1, 11)
Move elements down very often.

(2) For all elements in column j,


place element <i, j, value> in element <j, i, value>
Sparse Matrix Operations -Transpose
Sparse Matrix Operations -Transpose
Sparse Matrix Operations - Addition
To Add the matrices, simply traverse through both matrices element by element
and insert the smaller element (one with smaller row and col value) into the
resultant matrix. If we come across an element with the same row and column
value, simply add their values and insert the added data into the resultant matrix.
Sparse Matrix Operations - Addition

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.

• A polynomial can be thought of as an ordered list of non zero terms.


Each non zero term is a two-tupple which holds two pieces of
information:
• The exponent part
• The coefficient part
2. Polynomial Arithmetic using Linked List
-Addition
•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
3. 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;
{ //sequence in which nodes getting
node *f; deleted
int c=1;
printf("%d->",head->data);
while(head->next!=head)
head=f->next;
{
c=1; }
while(c!=m) printf("\n");
{
printf("Winner is:%d\n",head->data);
f=head; return;
head=head->next;
c++; }
}
Thank You…
21CSC201J
DATA STRUCTURES AND
ALGORITHMS

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:

Doubly circular linked list:


Circular Linked List

Advantages of a Circular linked list


• Entire list can be traversed from any node.
• Circular lists are the required data structure when we want a list to be accessed in a circle or
loop.
• Despite of being singly circular linked list we can easily traverse to its previous node, which is
not possible in singly linked list.

Disadvantages of Circular linked list


• Circular list are complex as compared to singly linked lists.
• Reversing of circular list is a complex as compared to singly or doubly lists.
• If not traversed carefully, then we could end up in an infinite loop.
• Like singly and doubly lists circular linked lists also doesn’t supports direct accessing of
elements.
Operations on Circular Linked List
• Creation of list
• Traversal of list
• Insertion of node
• At the beginning of list
• At any position in the list
• Deletion of node
• Deletion of first node
• Deletion of node from middle of the list
• Deletion of last node
• Counting total number of nodes
• Reversing of list
Creation and Traversal of a Circular List
Creation of a Circular List
Traversal of a Circular List
Few Exercises to Try Out
• For circular linked list write a function to:

• Insert a node at any position of the list and delete from the beginning of the list.
• insert_position(data,position);
• delete_front();

• Reverse the given circular linked link.


Thank You
21CSC201J
DATA STRUCTURES AND
ALGORITHMS

UNIT-2
Topic : Implementation of List ADT-
Array, Cursor based & linked
Implementing an ADT

• To implement an ADT, you need to choose:


• A data representation
• must be able to represent all necessary values of the ADT
• should be private
• An algorithm for each of the necessary operation:
• must be consistent with the chosen representation
• all auxiliary (helper) operations that are not in the contract should be private
• Remember: Once other people are using it
• It’s easy to add functionality
List - Implementation

• Lists can be implemented using:


• Arrays
• Linked List
• Cursor [Linked List using Arrays]
Arrays
• Array is a static data structure that represents a collection of fixed number of
homogeneous data items or
• A fixed-size indexed sequence of elements, all of the same type.
• The individual elements are typically stored in consecutive memory locations.
• The length of the array is determined when the array is created, and cannot be
changed.
Arrays (Contd..)

• Any component of the array can be inspected or updated by using its


index.
• This is an efficient operation
• O(1) = constant time
• The array indices may be integers (C, Java) or other discrete data
types (Pascal, Ada).
• The lower bound may be zero (C, Java), one (Fortran), or chosen by
the programmer (Pascal, Ada)
Different types of Arrays

• One-dimensional array: only one index is used


• Multi-dimensional array: array involving more than one index
• Static array: the compiler determines how memory will be allocated for the array
• Dynamic array: memory allocation takes place during execution
Insertion into Array

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

26 July 2023 Anna University, Chennai - 600 025 14


The List ADT

• 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

• The elements of a list are 34, 12, 52, 16, 12


• Find (52) -> 3
• Insert (20, 4) -> 34, 12, 52, 20, 16, 12
• Delete (52) -> 34, 12, 20, 16, 12
• FindKth (3) -> 20
Operations on List

• 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

• Need to define a size for array


• High overestimate (waste of space)
• insertion and deletion is very slow
• need to move elements of the list
• redundant memory space
• it is difficult to estimate the size of array
Linked List

• 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

• Need to know where the first node is


• the rest of the nodes can be accessed
• No need to move the elements in the list for insertion and deletion
operations
• No memory waste
Cursor Implementation

Problems with linked list implementation:


• Same language do not support pointers!
• Then how can you use linked lists ?
• new and free operations are slow
• Actually not constant time
• SOLUTION: Implement linked list on an array - called CURSOR
Cursor Implementation using ADT

• It is nothing but the linked list representation using array.


Operations:
1. Initialization of array
2. Insertion: Insert new element at position pointed by header (ZERO) and assign new position
which is null to header.
3. Deletion: Delete an element and assign that position to header (ZERO)
4. Traversal: Display the entire array
Title
Title
Title
Title
Title
Title
Title
Title
Cursor Implementation - Diagram

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


If M = 3, then M represents list (C, D, F)
21CSC201J
DATA STRUCTURES AND
ALGORITHMS

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.

• Input the position of the particular element to delete from an


array.

• Remove the particular element and shift the rest elements


position to the left side in an array.

• Display the resultant array after deletion or removal of the


element from an array.
Deletion
Searching
• One of the basic operations to be performed on an array
is searching.
• Searching an array means to find a particular element in
the array. The search can be used to return the position
of the element or check if it exists in the array.
• The simplest search to be done on an array is the linear
search. This search starts from one end of the array and
keeps iterating until the element is found, or there are
no more elements left (which means that the element
does not exist).
Searching
Sorting
• Create an array of fixed size
• Take n, a variable which stores the number of elements of the
array, less than maximum capacity of array.
• The array elements are in unsorted fashion
• In the nested loop, the each element will be compared to all
the elements below it
• In case the element is greater than the element present
below it, then they are interchanged
Sorting
Merging
• Input the length of both the arrays.
• Input the arrays elements from user.
• Copy the elements of the first array to the merged array when
initializing it.
• Copy the elements of the second array to the merged array
while initializing the second array.
• Display the merged array
Merging
Traversal
• Traversal means accessing each array element for a specific
purpose, either to perform an operation on them , counting
the total number of elements or else using those values to
calculate some other result.

• Since array elements is a linear data structure meaning that


all elements are placed in consecutive blocks of memory it is
easy to traverse them.
Traversal

You might also like