Types of Linked List and Operation on Linked List
In the previous blog, we have seen the structure and properties of a Linked List. In this blog, we will discuss the types of a linked list and basic operations that can be performed on a linked list.
Types of Linked List
Following are the types of linked list
- Singly Linked List.
- Doubly Linked List.
- Circular Linked List.
Singly Linked List
A Singly-linked list is a collection of nodes linked together in a sequential way where each node of the singly linked list contains a data field and an address field that contains the reference of the next node.
The structure of the node in the Singly Linked List is
class Node {
int data // variable to store the data of the node
Node next // variable to store the address of the next node
}
The nodes are connected to each other in this form where the value of the next variable of the last node is NULL i.e. next = NULL, which indicates the end of the linked list.
Doubly Linked List
A Doubly Linked List contains an extra memory to store the address of the previous node, together with the address of the next node and data which are there in the singly linked list. So, here we are storing the address of the next as well as the previous nodes.
The following is the structure of the node in the Doubly Linked List(DLL):
class DLLNode {
int val // variable to store the data of the node
DLLNode prev // variable to store the address of the previous node
DLLNode next // variable to store the address of the next node
}
The nodes are connected to each other in this form where the first node has prev = NULL and the last node has next = NULL.
Advantages over Singly Linked List-
- It can be traversed both forward and backward direction.
- The delete operation is more efficient if the node to be deleted is given. (Think! you will get the answer in the second half of this blog)
- The insert operation is more efficient if the node is given before which insertion should take place. (Think!)
Disadvantages over Singly Linked List-
- It will require more space as each node has an extra memory to store the address of the previous node.
- The number of modification increase while doing various operations like insertion, deletion, etc.
Circular Linked List
A circular linked list is either a singly or doubly linked list in which there are no NULL values. Here, we can implement the Circular Linked List by making the use of Singly or Doubly Linked List. In the case of a singly linked list, the next of the last node contains the address of the first node and in case of a doubly-linked list, the next of last node contains the address of the first node and prev of the first node contains the address of the last node.
Advantages of a Circular linked list
- The 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.
- We can easily traverse to its previous node in a circular linked list, which is not possible in a singly linked list. (Think!)
Disadvantages of Circular linked list
- If not traversed carefully, then we could end up in an infinite loop because here we don't have any NULL value to stop the traversal.
- Operations in a circular linked list are complex as compared to a singly linked list and doubly linked list like reversing a circular linked list, etc.
Basic Operations on Linked List
- Traversal: To traverse all the nodes one after another.
- Insertion: To add a node at the given position.
- Deletion: To delete a node.
- Searching: To search an element(s) by value.
- Updating: To update a node.
- Sorting: To arrange nodes in a linked list in a specific order.
- Merging: To merge two linked lists into one.
We will see the various implementation of these operations on a singly linked list.
Following is the structure of the node in a linked list:
class Node{
int data // variable containing the data of the node
Node next // variable containing the address of next node
}
Linked List Traversal
The idea here is to step through the list from beginning to end. For example, we may want to print the list or search for a specific node in the list.
The algorithm for traversing a list
- Start with the head of the list. Access the content of the head node if it is not null.
- Then go to the next node(if exists) and access the node information
- Continue until no more nodes (that is, you have reached the null node)
void traverseLL(Node head) {
while(head != NULL)
{
print(head.data)
head = head.next
}
}
Linked List node Insertion
There can be three cases that will occur when we are inserting a node in a linked list.
- Insertion at the beginning
- Insertion at the end. (Append)
- Insertion after a given node
Insertion at the beginning
Since there is no need to find the end of the list. If the list is empty, we make the new node as the head of the list. Otherwise, we we have to connect the new node to the current head of the list and make the new node, the head of the list.
// function is returning the head of the singly linked-list
Node insertAtBegin(Node head, int val)
{
newNode = new Node(val) // creating new node of linked list
if(head == NULL) // check if linked list is empty
return newNode
else // inserting the node at the beginning
{
newNode.next = head
return newNode
}
}
Insertion at end
We will traverse the list until we find the last node. Then we insert the new node to the end of the list. Note that we have to consider special cases such as list being empty.
In case of a list being empty, we will return the updated head of the linked list because in this case, the inserted node is the first as well as the last node of the linked list.
// the function is returning the head of the singly linked list
Node insertAtEnd(Node head, int val)
{
if( head == NULL ) // handing the special case
{
newNode = new Node(val)
head = newNode
return head
}
Node temp = head
// traversing the list to get the last node
while( temp.next != NULL )
{
temp = temp.next
}
newNode = new Node(val)
temp.next = newNode
return head
}
Insertion after a given node
We are given the reference to a node, and the new node is inserted after the given node.
void insertAfter(Node prevNode, int val)
{
newNode = new Node(val)
newNode.next = prevNode.next
prevNode.next = newNode
}
NOTE: If the address of the prevNode is not given, then you can traverse to that node by finding the data value.
Linked List node Deletion
To delete a node from a linked list, we need to do these steps
- Find the previous node of the node to be deleted.
- Change the next pointer of the previous node
- Free the memory of the deleted node.
In the deletion, there is a special case in which the first node is deleted. In this, we need to update the head of the linked list.
// this function will return the head of the linked list
Node deleteLL(Node head, Node del)
{
if(head == del) // if the node to be deleted is the head node
{
return head.next // special case for the first Node
}
Node temp = head
while( temp.next != NULL )
{
if(temp.next == del) // finding the node to be deleted
{
temp.next = temp.next.next
delete del // free the memory of that Node
return head
}
temp = temp.next
}
return head // if no node matches in the Linked List
}
Linked List node Searching
To search any value in the linked list, we can traverse the linked list and compares the value present in the node.
bool searchLL(Node head, int val)
{
Node temp = head // creating a temp variable pointing to the head of the linked list
while( temp != NULL) // traversing the list
{
if( temp.data == val )
return true
temp = temp.next
}
return false
}
Linked List node Updation
To update the value of the node, we just need to set the data part to the new value.
Below is the implementation in which we had to update the value of the first node in which data is equal to val and we have to set it to newVal.
void updateLL(Node head, int val, int newVal)
{
Node temp = head
while(temp != NULL)
{
if( temp.data == val)
{
temp.data = newVal
return
}
temp = temp.next
}
}
Suggested Problems to solve in Linked List
- Reverse linked list
- Middle of the Linked List
- Odd even linked List
- Remove Duplicates from Sorted List
- Merge Sort on Linked List
- Check if a singly linked list is a palindrome
- Detect and Remove Loop in a Linked List
- Sort a linked list using insertion sort
- Remove Nth Node from List End
Happy coding! Enjoy Algorithms.
In this tutorial, you will learn different operations on a linked list. Also, you will find implementation of linked list operations in C/C++, Python and Java.
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 that we will cover in this article.
- 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
Before you learn about linked list operations in detail, make sure to know about Linked List first.
Things to Remember about Linked List
- head points to the first node of the linked list
- next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list.
In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:
struct node {
int data;
struct node *next;
};
Linked List
- Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.
- A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory.
- The last node of the list contains pointer to the null.
Insertion in singly linked list at beginning
Inserting a new element into a singly linked list at beginning is quite simple. We just need to make a few adjustments in the node links. There are the following steps which need to be followed in order to inser a new node in the list at beginning.
- Allocate the space for the new node and store data into the data part of the node. This will be done by the following statements.
- Make the link part of the new node pointing to the existing first node of the list. This will be done by using the following statement.
- At the last, we need to make the new node as the first node of the list this will be done by using the following statement.
Data Structure and Algorithms - Linked List
A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array. Following are the important terms to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
LinkedList − A Linked List contains the connection link to the first link called First.
Linked List Data Structure
Practice Problems on Linked List
Recent Articles on Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list.
Topics :
- Singly Linked List
- Circular Linked List
- Doubly Linked List
Singly Linked List :
- Introduction to Linked List
- Linked List vs Array
- Linked List Insertion
- Linked List Deletion (Deleting a given key)
- Linked List Deletion (Deleting a key at given position)
- Write a function to delete a Linked List
- Find Length of a Linked List (Iterative and Recursive)
- Search an element in a Linked List (Iterative and Recursive)
- Write a function to get Nth node in a Linked List
- Nth node from the end of a Linked List
- Print the middle of a given linked list
- Write a function that counts the number of times a given int occurs in a Linked List
- Detect loop in a linked list
- Find length of loop in linked list
- Function to check if a singly linked list is palindrome
- Remove duplicates from a sorted linked list
- Remove duplicates from an unsorted linked list
- Swap nodes in a linked list without swapping data
- Pairwise swap elements of a given linked list
- Move last element to front of a given Linked List
- Intersection of two Sorted Linked Lists
- Intersection point of two Linked Lists.
- QuickSort on Singly Linked List
- Segregate even and odd nodes in a Linked List
- Reverse a linked list
More >>
Circular Linked List :
- Circular Linked List Introduction and Applications,
- Circular Linked List Traversal
- Split a Circular Linked List into two halves
- Sorted insert for circular linked list
- Check if a linked list is Circular Linked List
- Convert a Binary Tree to a Circular Doubly Link List
- Circular Singly Linked List | Insertion
- Deletion from a Circular Linked List
- Circular Queue | Set 2 (Circular Linked List Implementation)
- Count nodes in Circular linked list
- Josephus Circle using circular linked list
- Convert singly linked list into circular linked list
- Circular Linked List | Set 1 (Introduction and Applications)
- Circular Linked List | Set 2 (Traversal)
- Implementation of Deque using circular array
- Exchange first and last nodes in Circular Linked List
More >>
Doubly Linked List :
- Doubly Linked List Introduction and Insertion
- Delete a node in a Doubly Linked List
- Reverse a Doubly Linked List
- The Great Tree-List Recursion Problem.
- Copy a linked list with next and arbit pointer
- QuickSort on Doubly Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Merge Sort for Doubly Linked List
- Create a Doubly Linked List from a Ternary Tree
- Find pairs with given sum in doubly linked list
- Insert value in sorted way in a sorted doubly linked list
- Delete a Doubly Linked List node at a given position
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Remove duplicates from a sorted doubly linked list
- Delete all occurrences of a given key in a doubly linked list
- Remove duplicates from an unsorted doubly linked list
- Sort the biotonic doubly linked list
- Sort a k sorted doubly linked list
- Convert a given Binary Tree to Doubly Linked List | Set
- Program to find size of Doubly Linked List
- Sorted insert in a doubly linked list with head and tail pointers
- Large number arithmetic using doubly linked list
- Rotate Doubly linked list by N nodes
- Priority Queue using doubly linked list
- Reverse a doubly linked list in groups of given size
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Doubly Circular Linked List | Set 2 (Deletion)
More >>
Misc :
- Skip List | Set 1 (Introduction)
- Skip List | Set 2 (Insertion)
- Skip List | Set 3 (Searching and Deletion)
- Reverse a stack without using extra space in O(n)
- An interesting method to print reverse of a linked list
- Linked List representation of Disjoint Set Data Structures
- Sublist Search (Search a linked list in another list)
- How to insert elements in C++ STL List ?
- Unrolled Linked List | Set 1 (Introduction)
- A Programmer’s approach of looking at Array vs. Linked List
- How to write C functions that modify head pointer of a Linked List?
- Given a linked list which is sorted, how will you insert in sorted way
- Can we reverse a linked list in less than O(n)?
- Practice questions for Linked List and Recursion
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Squareroot(n)-th node in a Linked List
- Find the fractional (or n/k – th) node in linked list
- Find modular node in a linked list
- Construct a linked list from 2D matrix
- Find smallest and largest elements in singly linked list
- Arrange consonants and vowels nodes in a linked list
- Partitioning a linked list around a given value and If we don’t care about making the elements of the list “stable”
- Modify contents of Linked List
Quick Links :
- ‘Practice Problems’ on Linked List
- ‘Videos’ on Linked List
- ‘Quizzes’ on Linked List
If you still need more assistance with your placement preparation, have a look at our Complete Interview Preparation Course. The course has been designed by our expert mentors to help students crack the coding interview of top product or service-based organizations . You get access to premium lectures, 200+ coding questions bank, resume building tips, and lifetime access to the course content. So to make sure that your next programming interview doesn’t feel like an interrogation, enroll in Complete Interview Preparation and give a boost to your placement preparation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Insertion Sort for Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list.
Below is a simple insertion sort algorithm for a linked list.
1) Create an empty sorted (or result) list
2) Traverse the given list, do following for every node.
......a) Insert current node in sorted way in sorted or result list.
3) Change head of given linked list to head of sorted (or result) list.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
The main step is (2.a) which has been covered in the below post.
Sorted Insert for Singly Linked List
Below is implementation of above algorithm
C
// C program to sort link list
// using insertion sort
#include
#include
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
struct node* sorted = NULL;
void push(int val)
{
/* allocate node */
struct node* newnode
= (struct node*)malloc(sizeof(struct node));
newnode->data = val;
/* link the old list off the new node */
newnode->next = head;
/* move the head to point to the new node */
head = newnode;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(struct node* newnode)
{
/* Special case for the head end */
if (sorted == NULL || sorted->data >= newnode->data) {
newnode->next = sorted;
sorted = newnode;
}
else {
struct node* current = sorted;
/* Locate the node before the point of insertion
*/
while (current->next != NULL
&& current->next->data < newnode->data) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
// function to sort a singly linked list
// using insertion sort
void insertionsort()
{
struct node* current = head;
// Traverse the given linked list and insert every
// node to sorted
while (current != NULL) {
// Store next for next iteration
struct node* next = current->next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head to point to sorted linked list
head = sorted;
}
/* Function to print linked list */
void printlist(struct node* head)
{
while (head != NULL) {
printf("%d->", head->data);
head = head->next;
}
printf("NULL");
}
// Driver program to test above functions
int main()
{
push(5);
push(20);
push(4);
push(3);
push(30);
printf("Linked List before sorting:\n");
printlist(head);
printf("\n");
insertionsort(head);
printf("Linked List after sorting:\n");
printlist(head);
}
// This code is contributed by Sornodeep Chandra
|
C++
// C++ program to sort link list
// using insertion sort
#include
using namespace std;
struct Node {
int val;
struct Node* next;
Node(int x)
{
val = x;
next = NULL;
}
};
class LinkedlistIS {
public:
Node* head;
Node* sorted;
void push(int val)
{
/* allocate node */
Node* newnode = new Node(val);
/* link the old list off the new node */
newnode->next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion
// sort
void insertionSort(Node* headref)
{
// Initialize sorted linked list
sorted = NULL;
Node* current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != NULL) {
// Store next for next iteration
Node* next = current->next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(Node* newnode)
{
/* Special case for the head end */
if (sorted == NULL || sorted->val >= newnode->val) {
newnode->next = sorted;
sorted = newnode;
}
else {
Node* current = sorted;
/* Locate the node before the point of insertion
*/
while (current->next != NULL
&& current->next->val < newnode->val) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
/* Function to print linked list */
void printlist(Node* head)
{
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
}
};
// Driver program to test above functions
int main()
{
LinkedlistIS list;
list.head = NULL;
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
cout << "Linked List before sorting" << endl;
list.printlist(list.head);
cout << endl;
list.insertionSort(list.head);
cout << "Linked List After sorting" << endl;
list.printlist(list.head);
}
// This code is contributed by nirajgusain5
|
Java
// Java program to sort link list
// using insertion sort
public class LinkedlistIS
{
node head;
node sorted;
class node
{
int val;
node next;
public node(int val)
{
this.val = val;
}
}
void push(int val)
{
/* allocate node */
node newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion sort
void insertionSort(node headref)
{
// Initialize sorted linked list
sorted = null;
node current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != null)
{
// Store next for next iteration
node next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(node newnode)
{
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
node current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null && current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
void printlist(node head)
{
while (head != null)
{
System.out.print(head.val + " ");
head = head.next;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
LinkedlistIS list = new LinkedlistIS();
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
System.out.println("Linked List before Sorting..");
list.printlist(list.head);
list.insertionSort(list.head);
System.out.println("\nLinkedList After sorting");
list.printlist(list.head);
}
}
// This code is contributed by Rishabh Mahrsee
|
Python
# Python implementation of above algorithm
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# function to sort a singly linked list using insertion sort
def insertionSort(head_ref):
# Initialize sorted linked list
sorted = None
# Traverse the given linked list and insert every
# node to sorted
current = head_ref
while (current != None):
# Store next for next iteration
next = current.next
# insert current in sorted linked list
sorted = sortedInsert(sorted, current)
# Update current
current = next
# Update head_ref to point to sorted linked list
head_ref = sorted
return head_ref
# function to insert a new_node in a list. Note that this
# function expects a pointer to head_ref as this can modify the
# head of the input linked list (similar to push())
def sortedInsert(head_ref, new_node):
current = None
# Special case for the head end */
if (head_ref == None or (head_ref).data >= new_node.data):
new_node.next = head_ref
head_ref = new_node
else:
# Locate the node before the point of insertion
current = head_ref
while (current.next != None and
current.next.data < new_node.data):
current = current.next
new_node.next = current.next
current.next = new_node
return head_ref
# BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert
# Function to print linked list */
def printList(head):
temp = head
while(temp != None):
print( temp.data, end = " ")
temp = temp.next
# A utility function to insert a node
# at the beginning of linked list
def push( head_ref, new_data):
# allocate node
new_node = Node(0)
# put in the data
new_node.data = new_data
# link the old list off the new node
new_node.next = (head_ref)
# move the head to point to the new node
(head_ref) = new_node
return head_ref
# Driver program to test above functions
a = None
a = push(a, 5)
a = push(a, 20)
a = push(a, 4)
a = push(a, 3)
a = push(a, 30)
print("Linked List before sorting ")
printList(a)
a = insertionSort(a)
print("\nLinked List after sorting ")
printList(a)
# This code is contributed by Arnab Kundu
|
C#
// C# program to sort link list
// using insertion sort
using System;
public class LinkedlistIS
{
public node head;
public node sorted;
public class node
{
public int val;
public node next;
public node(int val)
{
this.val = val;
}
}
void push(int val)
{
/* allocate node */
node newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly
// linked list using insertion sort
void insertionSort(node headref)
{
// Initialize sorted linked list
sorted = null;
node current = headref;
// Traverse the given
// linked list and insert every
// node to sorted
while (current != null)
{
// Store next for next iteration
node next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(node newnode)
{
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
node current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null &&
current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
void printlist(node head)
{
while (head != null)
{
Console.Write(head.val + " ");
head = head.next;
}
}
// Driver code
public static void Main(String[] args)
{
LinkedlistIS list = new LinkedlistIS();
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
Console.WriteLine("Linked List before Sorting..");
list.printlist(list.head);
list.insertionSort(list.head);
Console.WriteLine("\nLinkedList After sorting");
list.printlist(list.head);
}
}
// This code contributed by Rajput-Ji
|
Javascript
// javascript program to sort link list
// using insertion sort
var head = null;
var sorted = null;
class node {
constructor(val) {
this.val = val;
this.next = null;
}
}
function push(val) {
/* allocate node */
var newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion sort
function insertionSort( headref) {
// Initialize sorted linked list
var sorted = null;
var current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != null) {
// Store next for next iteration
var next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a Note that this function expects a
* pointer to head_ref as this can modify the head of the input linked list
* (similar to push())
*/
function sortedInsert( newnode) {
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val) {
newnode.next = sorted;
sorted = newnode;
} else {
var current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null && current.next.val < newnode.val) {
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
function printlist( head) {
while (head != null) {
document.write(head.val + " ");
head = head.next;
}
}
// Driver program to test above functions
push(5);
push(20);
push(4);
push(3);
push(30);
document.write("Linked List before Sorting.. ");
printlist(head);
insertionSort(head);
document.write(" LinkedList After sorting ");
printlist(sorted);
// This code contributed by aashish2995
|
Output:
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Time and space complexity analysis:
In worst case we might have to traverse all nodes of the sorted list for inserting a node. And there are “n” such nodes.
Thus Time Complexity: O(n)*O(n)=O(n^2)
Space Complexity: No extra space is required depending on the size of the input. Thus Space complexity is constant- O(1).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Article Tags :
Linked List
Practice Tags : Linked List
Graphical Depiction of Node
A node is a name for each element in a linked list. A single node includes data as well as a pointer to the next node, which aids in the list’s structure. The head is the first node in the list; it points to the first node in the list and allows us to access all of the other elements in the list. The last node, commonly known as the tail, refers to NULL, which allows us to determine when the list comes to an end. The following is a graphical depiction of a node in a single linked list:
Let’s see the example of a graphical depiction of a singly linked list:
Basic Operations on Singly Linked Lists
On a Singly Linked List, the following operations are done:
To perform the above-mentioned operations, we must first create an empty list by using the following procedure:
Step 1: Ensure that all of the program’s header files are included.
Step 2: Create a list of all user-defined functions.
Step 3: Create a Node structure with two data members.
Step 4: Create a ‘head’ for the Node pointer and set it to NULL.
Step 5: Implement the main method by showing an operations menu and calling the appropriate functions in the main method to conduct the user’s chosen operation.
Insertion
After creating the empty list, we can perform an insertion operation on the list. The insertion operation can be done in three different ways in a single linked list.
- Inserting at the start of a list
- Inserting at the end of the list
- Inserting at a specific point in a list
Inserting at the Start of a List
Insertion at Start of Singly Linked List
The procedures below can be used to add a new node at the start of singly linked list:
Step 1: Generate a newNode using the supplied value.
Step 2: Verify that the list is empty (head == NULL).
Step 3: Set newNode→next = NULL and head = newNode if it’s empty.
Step 4: Set newNode→next = head and head = newNode if it is not empty.
Inserting at the End of the List
Insertion at End of Singly Linked List
The procedures below can be used to add a new node to the end of a single linked list:
Step 1: Make a newNode with the specified value and set newNode → next to NULL.
Step 2: Determine whether or not the list is empty (head == NULL).
Step 3: Set head = newNode if it is empty.
Step 4: If it’s not empty, create a temp node pointer and initialize it with head.
Step 5: Continue shifting the temp to the next node in the list until it reaches the last node (or until temp→next equals NULL).
Step 6: Set temp→next = newNode.
Inserting at a Specific Point in a List
Insertion at Specific Point of Singly Linked List
To insert a new node after a node in a single linked list, apply the instructions below:
Step 1: Construct a newNode using the supplied value.
Step 2: Verify that the list is empty (head == NULL).
Step 3: Set newNode next = NULL and head = newNode if it’s empty.
Step 4: If it’s not empty, create a temp node pointer and initialize it with head.
Step 5: Continue moving the temp to its next node until it reaches the node where we want to put the newNode (until temp1→data equals location, where location is the node value).
Step 6: Check if the temp has reached the last node or not at regular intervals. If you get to the last node, the message ‘Given node is not found in the list! Insertion is not possible!’ will appear and the function is terminated. If not, increment the temp to the next node.
Step 7: Finally, set ‘newNode→next = temp→next’ and ‘temp→next = newNode’ to their respective values.
Deletion
The deletion operation in a singly linked list may be done in three different ways. The following are the details:
- Delete from the start of the list
- Delete from the end of the list
- Delete a Particular Node
Delete from the Start of the List
Deleting First Node of Singly Linked List
To delete a node from the single linked list’s beginning, apply the procedures below:
Step 1: Check to see if the list is empty (head == NULL).
Step 2: If the list is empty, display the message ‘List is Empty! Deletion is not feasible!’, and the function is terminated.
Step 3: If it is not empty, create a temp Node reference and initialize it with head.
Step 4: Verify that the list only has one node (temp next == NULL).
Step 5: If TRUE, change head to NULL and remove temp (Setting Empty list conditions).
Step 6: If the answer is FALSE, set head = temp next and delete temp.
Delete from the End of the List
Deleting End Node of Singly Linked List
The procedures below can be used to remove a node from the single linked list’s end:
Step 1: Check to see if the list is empty (head == NULL).
Step 2: If the list is empty, display the message ‘List is Empty! Deletion is not feasible’, and the function is terminated.
Step 3:If it’s not empty, create two Node pointers, ‘temp1’ and ‘temp2,’ and set ‘temp1’ to head.
Step 4:Verify that the list only includes one Node (temp1 next == NULL).
Step 5: Determine if it is TRUE. Then remove temp1 and set head = NULL. Finally, the function is terminated. (Setting the criterion for an empty list).
Step 6: If the answer is FALSE. Set ‘temp2 = temp1’and then shift temp1 to the next node. Continue in this manner until you reach the last node on the list. (until next temp1 == NULL).
Step 7: Finally, remove temp1 and set temp2 next = NULL.
Delete a Particular Node
Deleting Particular Node of Singly Linked List
The steps below can be used to remove a specific node from the single linked list:
Step 1: Check to see if the list is empty (head == NULL).
Step 2:If the list is empty, display the message ‘List is Empty!!!’ Deletion is not possible’, and the function is terminated.
Step 3:If it’s not empty, create two Node pointers, ‘temp1’ and ‘temp2,’ and set ‘temp1’ to head.
Step 4: Continue dragging the temp1 until it approaches the last node or the particular node to be deleted. And before moving ‘temp1’ to the next node, always set ‘temp2 = temp1’.
Step 5: Once you’re at the last node, the message “Given node not found in the list! Deletion Not Pssible” appears. Finally, the function is terminated.
Step 6: If you’ve reached the particular node which you want to delete, check to see if the list has only one node.
Step 7: Set head = NULL and remove temp1 (free(temp1)) if list contains just one node and that is the node to be deleted.
Step 8: Check if temp1 is the first node in the list (temp1 == head) if the list has several nodes.
Step 9: If temp1 is the initial node, remove temp1 and shift the head to the next node (head = head→next).
Step 10: If temp1 isn’t the first node in the list (temp1→next == NULL), see if it’s the final one.
Step 11: Set temp2→next = NULL and remove temp1 (free(temp1)) if temp1 is the final node.
Step 12: Set temp2→next = temp1 →next and remove temp1 (free(temp1)) if temp1 is not the first or last node.
Display
The components of a single linked list can be displayed using the methods below:
Step 1: Determine whether or not the list is empty (head == NULL).
Step 2:If the list is empty, show “List is Empty!!!” and exit the method.
Step 3: If it is not empty, create a ‘temp’Node pointer and initialize it with head.
Step 4:Continue to display temp →data with an arrow (—>) until the temp reaches the last node.
Step 5: Finally, show temp →data with an arrow pointing to NULL (temp →data —> NULL).