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.
Insertion in singly linked list at the end
In order to insert a node at the last, there are two following scenarios which need to be mentioned.
- The node is being added to an empty list
- The node is being added to the end of the linked list
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.
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 program to sort link list
// using insertion sort
#include <stdio.h>
#include <stdlib.h>
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++ program to sort link list
// using insertion sort
#include <bits/stdc++.h>
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 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 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# 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
|
<script>
// 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..<br/>");
printlist(head);
insertionSort(head);
document.write("<br/>LinkedList After sorting<br/>");
printlist(sorted);
// This code contributed by aashish2995
</script>
|
Output:
Linked List before sorting 30 3 4 20 5 Linked List after sorting 3 4 5 20 30Time 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
Linked List Operations: Traverse, Insert and Delete
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; };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.
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
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):
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)
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.
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.
Insertion after a given node
We are given the reference to a node, and the new node is inserted after the given node.
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.
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.