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

Module -2 Updated

The document provides an overview of linked lists, including single, circular, double, and circular double linked lists, along with their operations such as traversal, insertion, deletion, and searching. It discusses the limitations of arrays and how linked lists serve as a flexible alternative for dynamic data storage. Additionally, it covers the implementation and performance analysis of linked lists and their applications in sparse matrix representation and polynomial addition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module -2 Updated

The document provides an overview of linked lists, including single, circular, double, and circular double linked lists, along with their operations such as traversal, insertion, deletion, and searching. It discusses the limitations of arrays and how linked lists serve as a flexible alternative for dynamic data storage. Additionally, it covers the implementation and performance analysis of linked lists and their applications in sparse matrix representation and polynomial addition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

Linked List

MODULE- 2
Single Linked List
Circular Linked List
Double Linked List
Circular Double Linked List
Applications of Linked List
Sparse Matrix Representation and its performance analysis
Addition of Polynomials and its performance analysis

DATA STRUCTURES AND ALGORITHMS | CSSE 2


Linked Lists: Single linked lists
List is a finite, ordered sequence of data items known as elements.
“Ordered” in this definition means that each element has a position in the
list.
In other words, there is a first element in the list, a second element, and so
on.
Each list element also has a data type.
Formally, a general list is of the form a1, a2, a3, ..., an. We say that the size
of this list is n.
We will call the special list of size 0 a null list
Limitations of Arrays
Fixed size: The size of an array is fixed. With a little extra effort, by
dynamically allocating an array in the heap.
Wastages of space: If the number of elements in an array is less than the
size of the array, which is fixed in advance, then it leads to wastage of space.
Sequential storage: An array allocates memory for all its elements chunked
together as one block of memory. For arrays, contiguous space is required.
Possibility of overflow: If the program ever needs to process more than
the size, there is a possibility of overflow and the code breaks.
Difficulty in insertion and deletion: Inserting new elements at the front
cannot be efficiently done because existing elements need to be shifted to
make room. Similar is the case for deletion also.
An appropriate solution to these problems is the linked list, which, at some
cost in memory space, permits lists to be constructed and modified easily.
A linked list is a sequence of elements in which every element has
link to its next element in the sequence.
Such an element is known as the node of a linked list.
Both the array and the linked list are alternative implementation options for a
sequence which is a collection of items with a defined order
Address of next node data
How to access the first node of Linked List?

• To access first node of linked list, create a head pointer.


• Assign the address of first node to head.
Array vs. Single Linked List (In
Terms of Representation)
Creating the Node of a Single
Linked List
//java
import java.util.*;
Class SinglyLinkedList
{
 Node is nothing but a structure.
private class Node()
 Link points to a struct node. (next node)
{
int data;
Node next;
}
public Node(int data)
{
this.data = data;
this.next = null;
}
Node head = null;
Hence, node is a self referential structure in Java. Node tail = null;
}
Output: 45
Creating a Single Linked List

public static void main (String[] args)


{
Linked list ll = new Linked list();
ll.head = new Node(45);
Node second = new Node(98);
Node third = new Node(3);

// now we will connect the nodes to form a


chain

ll.head.next = second;// 45 -->98


second.next = third;// 45 -->98 -->3
--> null
}
Head.link=2000
DATA STRUCTURES AND ALGORITHMS | CSSE 23
Linked List Operations: Traverse, Insert and Delete

• There are various linked list operations that allow us to perform different
actions on linked lists.
• For example, the insertion operation adds a new element to the linked list.

Here's a list of basic linked list operations:

• Traversal - access each element of the linked list


• Insertion - adds a new element to the linked list
• Deletion - removes the existing elements
• Search - find a node in the linked list
• Sort - sort the nodes of the linked list
Traverse a Linked List

Displaying the contents of a linked list is very simple.


We keep moving the temp node to the next one and display its contents.

When temp is NULL, we know that we have reached the end of the linked list so we
get out of the while loop.

public void display()


{
Node temp = head;
while(temp!=null)
{
System.out.println(temp.data + “ --> “);
temp = temp.next;
} List elements are -
System.out.println(“null“); 1 --->2 --->3 --->
}
Insert Elements to a Linked List

You can add elements to either the beginning, middle or end of the linked list.

1. Insert at the beginning //java


Allocate memory for new node public void insertBegin(int value )
Store data {
Change next of new node to point to head Node newNode = new Node(value);
Change head to point to recently created node newNode.next = head;
head = newNode;

Step 1 - Create a newNode with given value and newNode → previous


as NULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to newNode → next and
newNode to head.
Step 4 - If it is not Empty then, assign head to newNode → next and
newNode to head.
2. Insert at the End //java
Allocate memory for new node public void insertEnd(int value)
Store data {
Traverse to last node Node newNode= new Node(value);
Change next of last node to recently created node if(head==null)
{
Step 1 - Create a newNode with given value and head = newNode;
newNode → next as NULL. return;
Step 2 - Check whether list is Empty (head == }
NULL) Node temp = head;
Step 3 - If it is Empty, then assign NULL to while(temp.next !=null)
newNode → previous and newNode to head. {
Step 4 - If it is not Empty, then, define a node temp = temp.next;
pointer temp and initialize with head. }
Step 5 - Keep moving the temp to its next node temp.next = newNode;
until it reaches to the last node in the list (until }
temp → next is equal to NULL).
Step 6 - Assign newNode to temp → next and
temp to newNode → previous.
3. Insert at the Middle //java
Allocate memory and store data for new node public void insertMid(int pos,int value)
{
Traverse to node just before the required position of new Node newNode = new Node(value);
node.
Change next pointers to include new node in between if(pos==1)
{
newNode.next = head;
head = newNode;
}
else
{
Node temp.head;
int count = 1; //pos-1
while(count <pos-1)
{
temp = temp.next;
count++;
}
Node temp1 = temp.next;
temp.next = newNode;
newNode = temp1;
}

}
Delete from a Linked List
You can delete either from the beginning, end or from a particular position.

1. Delete from beginning //java


Point head to the second node //java
public Node deleteEnd()
head = head->link; public Node deleteBegin() {
{ if(head ==null ||
2. Delete from end if(head==null) head.next ==null)
Traverse to second last element { {
return null; return head;
Change its next pointer to null }
}
Node temp = head; Node temp = head;
Node temp1 = null;
head = head.next;
while(temp.next!=null)
temp.next = null; {
return temp; temp1 = temp;
} temp = temp.next;
}
temp1.next = null;
return temp;

}
3. Delete from middle //java
Traverse to element before the element to be deleted public Node deleteMid()
Change next pointers to exclude the node from the chain {
if(pos == 1)
{
// c head = head.next;
for(int i=2; i< position; i++) { }
if(temp->link!=NULL) { else
temp = temp->link; {
} Node temp = head;
} int count = 1;
while(count < pos-1)
{
temp->link = temp->link->link;
temp = temp.next;
count++;
}
Node temp1 = temp.next;
temp.next = temp1.next;

}
search an element
 To search an element in a Linked List, we need to traverse the entire Linked List.

 Compare each node with the data to be search and continue until a match is
found.

 Begin the search process from the first node as random access is not possible in
a Linked List.

public boolean search (int x)


{
Node temp = head; // Initialize current
while (temp!= NULL)
{
if (temp.data == x)
{
return true;
}
temp = temp.next;
}
return false;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 32


sort the elements

 Define a node current which will point to head.


 Define another node index which will point to node next to current.
 Compare data of current and index node.
 If current's data is greater than the index's data then, swap the data between them.
 Current will point to current->link and index will point to index->link.
 Continue this process until the entire list is sorted.

DATA STRUCTURES AND ALGORITHMS | CSSE 33


// c
int t;
Struct node *t1, *t2; //t1 – current node, t2 – index node
for(t1=head;t1->link!=NULL;t1=t1->link)
{
for(t2=head;t2->link!=NULL;t2=t2->link)
{
if(t2->data > t2->link->data)
{
t=t2->data;
t2->data=t2->link->data;
t2->link->data=t;
}
}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 34


Doubly Linked List
A doubly linked list is a type of linked list in which each node consists of 3
components:
*prev - address of the previous node
data - data item
*next - address of next node

DATA STRUCTURES AND ALGORITHMS | CSSE 35


Representation of Doubly Linked
List

//java creating a node


public class Node
{
int data;
Node previous;
Node next;
public Node(int data)
{
this.data = data;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 36


//creating node and doubly
linked list
public class DoublyLinkedList
{
Node head;
Node tail;
int length;
public class Node
{
int data;
Node previous;
Node next;
public Node(int data)
{
this.data = data;
}

}
Public DoublyLinkedList()
{
this.head = null;
this.tail = null;
this.length = 0;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 37


Operations on Double Linked List
Traversal
Insertion
Deletion
search

DATA STRUCTURES AND ALGORITHMS | CSSE 38


//java
Traversal public void displayForward()
{
if(head == null)
{
return;
}
Node temp = head;
while(temp!=null)
{
System.out.print(temp.data + “ --> “);
temp = temp.next;
}
System.out.println(“null”);
}
public void displayBackward()
{
if(tail == null)
{
return;
}
Node temp = tail;
while(temp!=null)
{
System.out.print(temp.data + “ --> “);
temp = temp.previous;
}
System.out.println(“null”);
}

DATA STRUCTURES AND ALGORITHMS | CSSE 39


Insertion on a Doubly Linked
List
Insertion at the beginning
Insertion in-between nodes
Insertion at the End

DATA STRUCTURES AND ALGORITHMS | CSSE 40


Insertion at the Beginning
Step 1 - Create a newNode with given value and newNode → previous as
NULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to
head.
Step 4 - If it is not Empty then, assign head to newNode → next and
newNode to head.

DATA STRUCTURES AND ALGORITHMS | CSSE 41


DATA STRUCTURES AND ALGORITHMS | CSSE 42
DATA STRUCTURES AND ALGORITHMS | CSSE 43
DATA STRUCTURES AND ALGORITHMS | CSSE 44
DATA STRUCTURES AND ALGORITHMS | CSSE 45
//java insert node at the beginning of a doubly linked list
public void insertBegin(int value)
{
Node newNode = new Node(value);
if(isEmpty())
{
tail = newNode;
}
else
{
head.previous = newNode;
}
newNode.next = head;
head = newNode;
length++;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 46


Insertion between the Nodes
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to both newNode → previous & newNode → next
and set newNode to head.
Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and initialize
temp1 with head.
Step 5 - Keep moving the temp1 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 temp1 is reached to the last node. If it is reached to
the last node then display 'Given node is not found in the list!!! Insertion not possible!!!'
and terminate the function. Otherwise move the temp1 to next node.
Step 7 - Assign temp1 → next to temp2, newNode to temp1 → next, temp1 to newNode →
previous, temp2 to newNode → next and newNode to temp2 → previous.

DATA STRUCTURES AND ALGORITHMS | CSSE 47


DATA STRUCTURES AND ALGORITHMS | CSSE 48
DATA STRUCTURES AND ALGORITHMS | CSSE 49
DATA STRUCTURES AND ALGORITHMS | CSSE 50
DATA STRUCTURES AND ALGORITHMS | CSSE 51
DATA STRUCTURES AND ALGORITHMS | CSSE 52
// java insert a node at a specific position in the
doubly else
linked list {
public void insertMid(int value, int pos) newNode.next = temp;
{ newNode.previous = temp.previous;
Node newNode = new Node(value); temp.previous.next = newNode;
if(pos == 1) temp.previous = newNode;
{ }
insertBegin(value);
}
else
{
Node temp = head;
int currpos = 1;
while(temp!=null && currpos<pos)
{
temp = temp.next;
currpos++;
}
if(temp == null)
{
insertEnd(value);
}
DATA STRUCTURES AND ALGORITHMS | CSSE 53
Inserting At End
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 assign NULL to newNode → previous and
newNode to 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 is equal to NULL).
Step 6 - Assign newNode to temp → next and temp to newNode → previous.

DATA STRUCTURES AND ALGORITHMS | CSSE 54


DATA STRUCTURES AND ALGORITHMS | CSSE 55
DATA STRUCTURES AND ALGORITHMS | CSSE 56
DATA STRUCTURES AND ALGORITHMS | CSSE 57
DATA STRUCTURES AND ALGORITHMS | CSSE 58
DATA STRUCTURES AND ALGORITHMS | CSSE 59
// java insertion at the end of a Doubly linked list
public void insertEnd(int value)
{
Node newNode = new Node(value);
if(isEmpty())
{
head = newNode;
}
else
{
tail.next = newNode;
newNode.previous = tail;
}
tail = newNode;
length++;

DATA STRUCTURES AND ALGORITHMS | CSSE 60


Deleting from Beginning of the
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 → previous == temp → next)
Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty
list conditions)
Step 6 - If it is FALSE, then assign head → next to head, NULL to head →
previous and delete temp.

DATA STRUCTURES AND ALGORITHMS | CSSE 61


DATA STRUCTURES AND ALGORITHMS | CSSE 62
// delete a node at the beginning of a
doubly linked list
public void deleteBegin()
{
if(head == null)
{
System.out.println(“linked list is empty”);
}
Node temp = head;
if(head == tail)
{
tail = null;
}
else
{
head.next.previous = null;
}
head = head. next;
temp.next = null;
return temp;

}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 63


Deleting from End
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 has only one Node (temp → previous and temp →
next both are NULL)
Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate
from the function. (Setting Empty list condition)
Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node in
the list. (until temp → next is equal to NULL)
Step 7 - Assign NULL to temp → previous → next and delete temp.

DATA STRUCTURES AND ALGORITHMS | CSSE 64


DATA STRUCTURES AND ALGORITHMS | CSSE 65
DATA STRUCTURES AND ALGORITHMS | CSSE 66
DATA STRUCTURES AND ALGORITHMS | CSSE 67
// java delete a node at the end
of the doubly linked list
public void deleteEnd()
{
if(isEmpty())
{
System.out.println(“ linked list is empty”);
}
Node temp = tail;
if(head == tail)
{
head = null;
}
else
{
tail.previous.next = null;
}
tail = tail.previous;
temp.previous = null;
length--;
return temp;

}
DATA STRUCTURES AND ALGORITHMS | CSSE 68
Deleting a Specific Node
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 - Keep moving the temp until it reaches to the exact node to be deleted or to the last 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 fuction.

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 which is to be deleted then set head to NULL and delete temp (free(temp)).

Step 8 - If list contains multiple nodes, then check whether temp is the first node in the list (temp == head).

Step 9 - If temp is the first node, then move the head to the next node (head = head → next), set head of previous to NULL (head →
previous = NULL) and delete temp.

Step 10 - If temp is not the first node, then check whether it is the last node in the list (temp → next == NULL).

Step 11 - If temp is the last node then set temp of previous of next to NULL (temp → previous → next = NULL) and delete temp
(free(temp)).

Step 12 - If temp is not the first node and not the last node, then set temp of previous of next to temp of next (temp → previous → next =
temp → next), temp of next of previous to temp of previous (temp → next → previous = temp → previous) and delete temp (free(temp)).

DATA STRUCTURES AND ALGORITHMS | CSSE 69


DATA STRUCTURES AND ALGORITHMS | CSSE 70
// delete a node at a specific position
in a doubly linked list if(temp == null)
public void deleteMid(int pos) {
{ System.out.println(“pos wrong”);
if(head == null) return;
{ }
System.out.println(“linked list is empty”);
} if(temp == tail)
if(pos == 1 ) {
{ deleteEnd();
deleteBegin(); return;
return; }
}
Node temp = head; temp.previous.next = temp.next;
int count = 1; temp.next.previous = temp.previous;
while(temp!=null && count !=pos) temp.previous = null;
{ temp.next = null;
temp = temp.next;
count++; }
}

DATA STRUCTURES AND ALGORITHMS | CSSE 71


Reversing the Doubly Linked List

DATA STRUCTURES AND ALGORITHMS | CSSE 72


DATA STRUCTURES AND ALGORITHMS | CSSE 73
DATA STRUCTURES AND ALGORITHMS | CSSE 74
DATA STRUCTURES AND ALGORITHMS | CSSE 75
DATA STRUCTURES AND ALGORITHMS | CSSE 76
// java reversing the doubly linked list

public Node reverse()


{
Node ptr1 = head;
Node ptr2 = ptr1.next;

ptr1.next = null;
ptr1.prev = ptr2;

while(ptr2 != null)
{
ptr2.prev = ptr2.next;
ptr2.next = ptr1;
ptr1 = ptr2;
ptr2 = ptr2.prev;
}
head = ptr1;
return head;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 77


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.
//java
class Node
{
int data;
Node next;

Node(int data)
{
this.data = data;
this.next = null;
}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 78


Operations
1.Insertion
2.Deletion
3.Display

DATA STRUCTURES AND ALGORITHMS | CSSE 79


Inserting At Beginning

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 -
◦ newNode → next =head
◦ head = newNode
◦ temp → next = head

DATA STRUCTURES AND ALGORITHMS | CSSE 80


public void insertBegin(int data)
{
Node newNode = new Node(data);
if(head == null)
{
head = newNode;
newNode . next = head;
}
else
{
temp = head;
while(temp.next != head)
{
temp = temp.next;
}
newNode .next = head;
temp .next = newNode;
head = newNode;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 81


Inserting At End

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 –
temp → next = newNode
newNode → next = head

DATA STRUCTURES AND ALGORITHMS | CSSE 82


public void insertEnd(int data)
{
Node newNode = new Node(data);
if(head == null)
{
head = newNode;
newNode .next = head;
}
else
{
temp = head;
while(temp.next != head)
{
temp = temp next;
}
temp.next = newNode;
newNode.next = head;
}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 83


Inserting At Specific location
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!!!
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
temp → next = newNode.

DATA STRUCTURES AND ALGORITHMS | CSSE 84


(or)
p=head;

DATA STRUCTURES AND ALGORITHMS | CSSE 85


DATA STRUCTURES AND ALGORITHMS | CSSE 86
public void insertMid(int data,int pos )
{
temp1= head ;
temp2= temp1.next;
while(pos>1)
{
temp1=temp1.next;
pos--;
}
if(temp1==temp2 )
{
newnode.next=temp2.next;
temp2.next = newnode;
temp2=temp2.next;
}
else
{
newNode.next = temp.next;
temp.next = newNode;
}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 87


Deleting the First Node

DATA STRUCTURES AND ALGORITHMS | CSSE 88


public void deleteBegin()
{
if(head == null)
{
System.out.println(“list is empty");
return;
}
else if(head.next == head)
{
head = null;
System.out.println(“Node deleted");
return;
}
else
{
Node ptr = head;
while(ptr.next != head)
{
ptr = ptr.next;
}
ptr.next = head.next;
head = ptr.next;
System.out.println(“node deleted”);
}

DATA STRUCTURES AND ALGORITHMS | CSSE 89


Deleting the Last Node

DATA STRUCTURES AND ALGORITHMS | CSSE 90


public void deleteEnd()
{
if(head==null)
{
System.out.println(“list is empty”);
}
else if (head.next == head)
{
head = null;
System.out.println(“node deleted");
}
else
{
Node ptr1 = head;
while(ptr1.next != head)
{
ptr2 = ptr1;
ptr1 = ptr1.next;
}
ptr2.next = ptr1.next;
System.out.println(“node deleted”);
}
}
DATA STRUCTURES AND ALGORITHMS | CSSE 91
Deleting the Intermediate Node

DATA STRUCTURES AND ALGORITHMS | CSSE 92


public void deleteMid(int pos)
if(tail==null)
return tail;
Node temp1 = head;
if(tail.next==tail)
{
tail=null;
return tail;
}
while(pos>2)
{
temp1=temp1.next;
pos--;
}
Node temp2=temp1.next;
temp1.next=temp2.next;
if(temp2==tail)
{
tail=temp1;
}
temp2=null;
return tail;
}
DATA STRUCTURES AND ALGORITHMS | CSSE 93
{
if(ptr->data == item)
{
struct node* ptr;
printf("item found at location %d ",i+1);
int item,i=0,flag=0;

ptr = head; flag=1;

if(ptr == NULL) break;

{ }
printf("\nEmpty List\n"); else
} {
else flag=0;
{ }
printf("\nEnter item which you want to search?\n");
i++;
scanf("%d",&item);
ptr = ptr -> next;
if(head ->data == item)
}
{
}
printf("item found at location %d",i+1);
if(flag != 1)
flag=1;
{
}
printf("Item not found\n");
else

{ }

while (ptr->next != head) }

DATA STRUCTURES AND ALGORITHMS | CSSE 94


Counting the Number of Elements

DATA STRUCTURES AND ALGORITHMS | CSSE 95


//java counting the no. of elements
public int countNodes()
{
Node temp = tail.next;
int count = 0;
while( temp != tail)
{
count ++;
temp = temp.next;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 96


Circular Double Linked List
Circular doubly linked list is a more complexed type of data structure.
A node contain pointers to its previous node as well as the next node.
Circular doubly linked list doesn't contain NULL in any of the node.
The last node of the list contains the address of the first node of the list.
The first node of the list also contain address of the last node in its previous
pointer.

DATA STRUCTURES AND ALGORITHMS | CSSE 97


//doubly linked list node
Class Node
{
int data;
Node next; // Pointer to next node
Node prev; // Pointer to previous node
Node(int data )
{
this.data = data;
this.next = null;
this.previous = null;
}

} DATA STRUCTURES AND ALGORITHMS | CSSE 98


Operations
Insertion at beginning
Insertion at end
Deletion at beginning
Deletion at end

DATA STRUCTURES AND ALGORITHMS | CSSE 99


Insertion at the Beginning

DATA STRUCTURES AND ALGORITHMS | CSSE 100


Public void insertBegin(int item)
{ else
Node newNode = new Node(item) {
if(newNode == null) Node temp = head;
{ while(temp.next != head)
System.out.println(“overflow”); {
return; temp = temp.next;
} }
if(head==null temp.next = newNode;
{ newNode.prev = temp;
head = newNode; head .prev = newNode;
newNode.next = head; newNode.next = head;
newNode.prev = head; head = newNode;
} }
System.out.println(“Node inserted ”);
}

DATA STRUCTURES AND ALGORITHMS | CSSE 101


Insertion at the end

DATA STRUCTURES AND ALGORITHMS | CSSE 102


public void insertionEnd(int item) else
{ {
Node newNode = new Node(item); Node temp = head;
if(newNode == null) while(temp.next !=head)
{ {
System.out.println(“overflow”); temp = temp.next;
return; }
} temp.next = newNode;
if(head == null) newNode .prev=temp;
{ head.prev = newNode;
head = newNode; newNode.next = head;
newNode.next = head; }
newNode.prev = head; }
} System.out.println(“Node inserted”);
}

DATA STRUCTURES AND ALGORITHMS | CSSE 103


Deletion at beginning

DATA STRUCTURES AND ALGORITHMS | CSSE 104


else
public void deletionBegin() {
{ Node temp = head;
if(head ==null) while(temp. next != head)
{ {
System.out.println(“UNDERFLOW”); temp = temp.next;
return; }
} temp.next = head.next;
else if(head.next == head) head.next.prev = temp;
{ head = temp.next;
head = null; }
System.out.println(“Node deleted”); System.out.println(“Node deleted”);
return;
}

DATA STRUCTURES AND ALGORITHMS | CSSE 105


Deletion at end

DATA STRUCTURES AND ALGORITHMS | CSSE 106


public void deletionEnd()
else
{
{
if(head == null)
Node temp = head;
{
if(temp.next != head)
System.out.println(“UNDERFLOW”);
{
return;
temp = temp.next;
}
}
else if(head.next == head)
temp.prev.next = head;
{
head.prev = temp.prev;
head = null;
System.out.println(“Node deleted”);
System.out.println(“Node deleted”);
}
return;
}
}

DATA STRUCTURES AND ALGORITHMS | CSSE 107


Applications
Linked Lists can be used to implement Stacks , Queues.
Linked Lists can also be used to implement Graphs. (Adjacency list
representation of Graph).
A polynomial can be represented in an array or in a linked list by simply storing
the coefficient and exponent of each term.
However, for any polynomial operation , such as addition or multiplication of
polynomials , linked list representation is more easier to deal with.
Linked lists are useful for dynamic memory allocation.
The real life application where the circular linked list is used is our Personal
Computers, where multiple applications are running.
All the running applications are kept in a circular linked list and the OS gives a
fixed time slot to all for running. The Operating System keeps on iterating over
the linked list until all the applications are completed.
Sparse Matrix Representation
and its performance analysis
In computer programming, 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.
Sparse matrix is a matrix which contains very few non-zero elements.

DATA STRUCTURES AND ALGORITHMS | CSSE 109


When a sparse matrix is represented with a 2-dimensional array, we waste a
lot of space to represent that matrix.
For example, consider a matrix of size 100 X 100 containing only 10 non-zero
elements.
In this matrix, only 10 spaces are filled with non-zero values and remaining
spaces of the matrix are filled with zero.
That means, totally we allocate 100 X 100 X 2 = 20000 bytes of space to
store this integer matrix.
To access these 10 non-zero elements we have to make scanning for 10000
times.

DATA STRUCTURES AND ALGORITHMS | CSSE 110


Sparse Matrix Representations
A sparse matrix can be represented by using TWO representations:

Array Representation
Linked Representation

DATA STRUCTURES AND ALGORITHMS | CSSE 111


Array Representation
In this representation, we consider only non-zero values along with their row
and column index values.
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.
For example, consider a matrix of size 5 X 6 containing 6 number of non-zero
values. This matrix can be represented as

Here the first row in


the right side table is
filled with values 5, 6 &
6 which indicates that it
is a sparse matrix with
5 rows, 6 columns & 6
non-zero values.

DATA STRUCTURES AND ALGORITHMS | CSSE 112


public class SparseMatrix
{
public static void main (String [] args)
{ // Defining final matrix
// Sparse matrix having size 4*5 int [] [] matrix = new int[3][size];
int sparse_matrix[][] = int k=0;
{ // Computing final matrix
{0 , 0 , 7 , 0 , 9 }, for(int i=0; i<4; i++)
{0 , 0 , 5 , 7 , 0 }, {
{0 , 0 , 0 , 0 , 0 }, for(int j=0; j<5; j++)
{0 , 2 , 3 , 0 , 0 } {
}; if(sparse_matrix[i][j]!=0)
// size of matrix {
int size = 0; matrix[0][k] = i;
for(int i=0; i<4; i++) matrix[1][k] = j;
{ matrix[2][k] = sparse_matrix[i][j];
for(int j=0; j<5; j++) k++;
{ }
if(sparse_matrix[i][j]!=0) }
{ }
size++;
}
}
} DATA STRUCTURES AND ALGORITHMS | CSSE 113
// Displaying the final matrix
for(int i=0 ;i<3; i++)
{
for(int j=0; j<size; j++)
{
System.out.print(matrix[i][j] + “\t”);
}
System.out.println();
}

Output:
0 0 1 1 3 3
2 4 2 3 1 2
7 9 5 7 2 3

DATA STRUCTURES AND ALGORITHMS | CSSE 114


Construct Sparse matrix using Array
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2,6,0,0}

DATA STRUCTURES AND ALGORITHMS | CSSE 115


Linked List Representation
In linked list representation, linked list data structure is used to represent a
sparse matrix. In linked list representation, each node consists of four fields
whereas, in array representation, there are three fields, i.e., row, column,
and value. The following are the fields in the linked list:

Row: It is an index of row where a non-zero element is located.


Column: It is an index of column where a non-zero element is located.
Value: It is the value of the non-zero element which is located at the index
(row, column).
Next node: It stores the address of the next node.

DATA STRUCTURES AND ALGORITHMS | CSSE 116


DATA STRUCTURES AND ALGORITHMS | CSSE 117
// Node to represent sparse matrix
import java.util.*;
class Node
{
int value; else
int rowPosition; {
int columnPosition; while (temp.next != null)
Node next; temp = temp.next;
Node(int value , int rowPosition, int columnPosition) // Create new node dynamically
{ r.value = non_zero_element;
this.value = value; r.row_position = row_index;
this.rowPosition = rowPosition; r.column_postion = column_index;
this.columnPosition = coulmnPosition; r.next = null;
this.next = null; temp.next = r;
}
} }
class SparseMatrix { }
Node start;
// Method to create new node
public void create_new_node(int value, int rowPosition , int columnPosition)
{
Node temp = start;
Node r;
if (temp == null)
{
// Create new node dynamically
temp.value = non_zero_element;
temp.row_position = row_index;
temp.column_postion = column_index;
temp.next =null;
start = temp;

DATA STRUCTURES AND ALGORITHMS | CSSE 118


// This function prints contents of linked list
// starting from start
public static void PrintList( Node start) public static void main (String[] args)
{ {
Node temp = start; // Assume 4x5 sparse matrix
System.out.print("row_position: "); int sparseMatric[][] =
while(temp != null) {
{ {0 , 0 , 1 , 2 },
{3 , 0 , 0 , 0 },
System.out.print( temp.row_position); {0 , 4 , 5 , 0 },
temp = temp.next; {0 , 6 , 0 , 0 }
} };
System.out.println(“ ");
/* Start with the empty list */
System.out.print("column_postion: "); struct Node* start = NULL;
temp = start;
while(temp !=null) for (int i = 0; i < 4; i++)
{ for (int j = 0; j < 4; j++)
System.out.print( temp.column_postion);
temp = temp.next; // Pass only those values which are non - zero
} if (sparseMatric[i][j] != 0)
System.out.print(“ "); create_new_node(i,j, sparseMatric[i][j], i, j);
System.out.print("Value: ");
temp = start; PrintList(start);
while(temp !=null)
{
System.out.print( temp.value); }
temp = temp.next; Output:
} row_position: 001223
System.out.print(“ "); column_postion: 230121
} Value: 123456

DATA STRUCTURES AND ALGORITHMS | CSSE 119


Construct Sparse matrix using Linked List

{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }

DATA STRUCTURES AND ALGORITHMS | CSSE 120


Linked list implementation of
stack
The major problem with the stack implemented using an array is, it works
only for a fixed number of data values.
i.e. the amount of data must be specified at the beginning of the
implementation itself.
A stack data structure can be implemented by using a linked list data
structure which can work for an unlimited number of values.
So, there is no need to fix the size at the beginning of the implementation.
Linked list allocates the memory dynamically.
Implement a stack using single linked list concept. all the single linked list
operations perform based on Stack operations LIFO(last in first out)
In linked list implementation of stack, the nodes are maintained non-
contiguously in the memory.
Each node contains a pointer to its immediate successor node in the stack.
Stack is said to be overflown if the space left in the memory heap is not
enough to create a node.
In linked list implementation of a stack, every new element is inserted as
'top' element.
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.
Operations
push() : Insert the element into linked list nothing but which is the top node
of Stack.
pop() : Return top element from the Stack and move the top pointer to the
second node of linked list or Stack.
peek(): Return the top element.
display(): Print all element of Stack.
Node structure for stack
class node
{
int data;
node next;
}
node top = null;

To point the last inserted node


top = NULL indicates the empty stack.
Adding a node to the stack
(Push operation)
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.
void push(int value) {
Node newNode = new Node(value);
newNode.data = value;
if(top == null) {
newNode.next = null;
} else {
newNode.next = top;
}
top = newNode;
Sop("\nInsertion is Success!!!\n");
}
Deleting a node from the stack
(POP operation)
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 top to the next node by
top=temp->next
Repeat the same until temp reaches to the first node in the stack.
(temp → next != NULL).
Step 5 - Finally! Display 'temp → data ---> NULL'.
void pop() {
if (top == null) {
Sop("\nStack is Empty!!!\n");
} else {
Node temp = top;
Sop("\nDeleted element: %d", temp.data);
top = temp.next;
}
}
Displaying stack of elements
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'.
void display() {
if(top == null) {
Sop("\nStack is Empty!!!\n");
} else {
Node temp = top;
while (temp != null) {
Sop(temp.data "--->");
temp = temp.next;
}
Sop(“null”);
}
}
void main() {
import java.util.Scanner; Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
class Node { int choice, value;
int data;
Node next; Sop("\n:: Stack using Linked List ::\n");
} while(true){
Node top = null; Sop("\n****** MENU ******\n");
Sop("1. Push\n2. Pop\n3. Display\n4. Exit\n");
void push(int value){ Sop("Enter your choice: ");
} choice = scanner.nextInt();
void pop(){
} switch(choice){
void display(){ case 1: Sop("Enter the value to be insert: ");
} value = scanner.nextInt();
stack.push(value);
break;
case 2: stack.pop(); break;
case 3: stack.display(); break;
case 4: System.exit(0);
default: Sop("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value) {
Node newNode = new Node(value);
if(top == null) {
newNode.next = null;
}else {
newNode.next = top;
} top = newNode;
Sop("\nInsertion is Success!!!\n");
}

void pop() {
if(top == null){
sop("\nStack is Empty!!!\n");
} else {
Node temp = top;
Sop("\nDeleted element:", temp.data);
top = temp.next;
}
}

void display() {
if(top == null) {
Sop("\nStack is Empty!!!\n");
} else {
Node temp = top;
while(temp != null){
Sop("--->“ temp.data);
temp = temp.next;
}
Sop(“NULL”);
}
}
Queue Using Linked List
The major problem with the queue implemented using an array is, It will
work for an only fixed number of data values.
That means, the amount of data must be specified at the beginning itself.
Queue using an array is not suitable when we don't know the size of data
which we are going to use.
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.
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’.
The order of elements inserted is 10, 15, 22 and 50.
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

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
rear = newNode.
deQueue() - Deleting an Element from 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
delete 'temp’
free(temp)
display() - Displaying the elements of 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'.
import java.util.Scanner;
class Node { choice = scanner.nextInt();
int data; switch (choice) {
Node next; case 1: Sop("Enter the value to be insert: ");
} value = scanner.nextInt();
class Queue { queue.insert(value);
Node front = null; break;
Node rear = null; case 2:
queue.delete();
void insert(int value){ break;
} case 3:
void delete(){ queue.display();
} break;
void display(){ case 4:
} System.exit(0);
break;
void main() { default:
Scanner scanner = new Scanner(System.in); Sop("Wrong selection!!! Please try again!!!");
Queue queue = new Queue(); }
int choice, value; }
Sop("\n:: Queue Implementation using Linked List ::\n"); }
while(true) {
Sop("\n****** MENU ******\n");
Sop("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
Sop("Enter your choice: ");
void insert(int value)
{
Node newNode = new Node(value);
if (front == null) {
front = rear = newNode;
} else {
rear.next = newNode;
rear = newNode;
}
Sop("\nInsertion is Success!!!\n");
}
void delete() {
if (front == null) {
Sop("\nQueue is Empty!!!");
} else {
Node temp = front;
front = front.next;
Sop("\nDeleted element: " temp.data);
}
}
void display()
{
if(front == null) {
Sop("\nQueue is Empty!!!\n");
} else{
Node temp = front;
while(temp.next != null) {
Sop(temp.data "--->");
temp = temp.next;
}
Sop(temp.data "--->NULL");
}
}
DATA STRUCTURES AND ALGORITHMS | CSSE 142
DATA STRUCTURES AND ALGORITHMS | CSSE 143
DATA STRUCTURES AND ALGORITHMS | CSSE 144
DATA STRUCTURES AND ALGORITHMS | CSSE 145
DATA STRUCTURES AND ALGORITHMS | CSSE 146

You might also like