Why is deleting in a Singly Linked List O(1)?
Last Updated :
09 Mar, 2023
How does deleting a node in Singly Linked List work?
To delete a node from a linked list we need to break the link between that node and the one pointing to that node. Assume node X needs to be deleted and node Y is the one pointing to X. So, we will need to break the link between X and Y and Y will point to the node which was being pointed by X.
Types of Deletion of a node from Linked List
There can be three types of deletions:
- Deletion from the beginning of the linked list
- Deletion from the end of the linked list
- Deletion from in between the beginning and the end.
All the cases do not take O(1) time. Check the below section to find the time complexities of different operations.
Time Complexities of different deletion operations
Deletion from the beginning:
- Point head to the next node
- Time Complexity: O(1)
Deletion from the end:
- Traverse to the second last element
- Change its next pointer to NULL.
- Time Complexity: O(N)
Delete from the middle of a linked list
- Traverse to the element which is just before the element to be deleted
- Change the next pointers to exclude the node from the list
- Time Complexity: O(N)
When Deletion in a Singly Linked List takes O(1) time?
There are 3 cases when deleting in a singly linked list is O(1), because we do not have to traverse the list.
First case: When we have the pointer pointing to the node which needs to be deleted, let's call it prev. So, we have to do,
- curr = prev->next
- prev->next = curr->next
- curr->next = NULL
- delete curr
Since curr is the node that is deleted from the singly linked list.
Second case: When we have to delete the first/start/head node, let's call it head. So, we have to do,
Hence head is pointing to the next node.
Third case: When we have to delete the last/end/tail node, let's call it tail. So, we have to do,
This is only possible if we maintain an extra pointer except the head i.e., tail for referencing the last node of the linked list. But we can do this only once because after doing this we lose the reference of the last node and there is no way to find the reference of the new last node in O(1) in a singly linked list. In a doubly linked list, it is possible as it contains the previous pointer.
Complexities of deletion from Linked List
Below is the implementation of different deletion operations in a singly linked list:
C++
// C++ code to implement the approach
#include <iostream>
using namespace std;
// Creating a class Node
class Node {
public:
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
// Function to delete the start node
void deleteFromStart(Node*& head)
{
head = head->next;
}
// Function to delete the middle node
void deleteGivenNode(Node*& head, int val)
{
if (head->data == val) {
head = head->next;
}
Node *temp = head, *prev = NULL;
while (temp->data != val) {
prev = temp;
temp = temp->next;
}
prev->next = temp->next;
}
// Function to delete the last node
void deleteFromEnd(Node* head)
{
Node* temp = head;
while (temp->next->next != NULL) {
temp = temp->next;
}
temp->next = NULL;
}
// Function to print the list
void printList(Node* head)
{
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Driver Code
int main()
{
Node* head = new Node(10);
Node* second = new Node(20);
Node* third = new Node(30);
Node* fourth = new Node(40);
head->next = second;
second->next = third;
third->next = fourth;
cout << "Original list: ";
printList(head);
deleteFromStart(head);
cout << "List after deleting the starting node: ";
printList(head);
deleteFromEnd(head);
cout << "List after deleting the ending node: ";
printList(head);
deleteGivenNode(head, 30);
cout << "List after deleting the given node: ";
printList(head);
}
Java
// Java code to implement the approach
// Creating a class Node
class Node {
public int data;
public Node next;
public Node(int d) {
data = d;
next = null;
}
}
public class Main {
// Function to delete the start node
public static Node deleteFromStart(Node head) {
head = head.next;
return head;
}
// Function to delete the given node
public static void deleteGivenNode(Node head, int val) {
if (head.data == val) {
head = head.next;
}
Node temp = head, prev = null;
while (temp.data != val) {
prev = temp;
temp = temp.next;
}
prev.next = temp.next;
}
// Function to delete the last node
public static void deleteFromEnd(Node head) {
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
// Function to print the list
public static void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Driver Code
public static void main(String[] args) {
Node head = new Node(10);
Node second = new Node(20);
Node third = new Node(30);
Node fourth = new Node(40);
head.next = second;
second.next = third;
third.next = fourth;
System.out.print("Original list: ");
printList(head);
head = deleteFromStart(head);
System.out.print("List after deleting the starting node: ");
printList(head);
deleteFromEnd(head);
System.out.print("List after deleting the ending node: ");
printList(head);
deleteGivenNode(head, 30);
System.out.print("List after deleting the given node: ");
printList(head);
}
}
Python3
# Python code to implement the approach
# Creating a class Node
class Node:
def __init__(self,val):
self.val = val
self.next = None
# Function to delete the start node
def deleteFromStart(head):
if head != None:
head = head.next
return head
# Function to delete the middle node
def deleteGivenNode(head,val):
if head.val == val: head = head.next
curr = head
prev = None
while curr and curr.val != val:
prev = curr
curr = curr.next
prev.next = curr.next
# Function to delete the last node
def deleteFromEnd(head):
curr = head
while curr.next and curr.next.next != None:
curr = curr.next
curr.next = None
# Prints the stack
def printList(head):
if head == None:
print('List is Empty')
return
curr = head
while curr != None:
print(curr.val,end = ' ')
curr = curr.next
print()
# Driver code
head = Node(10)
second = Node(20)
third = Node(30)
fourth = Node(40)
head.next = second
second.next = third
third.next = fourth
print("Original list: ")
printList(head)
head = deleteFromStart(head)
print("List after deleting the starting node: " )
printList(head)
deleteFromEnd(head)
print("List after deleting the ending node: " )
printList(head)
deleteGivenNode(head, 30)
print("List after deleting the given node: ")
printList(head)
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
// C# code to implement the approach
// Creating a class Node
class Node {
public int data;
public Node next;
public Node(int d) {
data = d;
next = null;
}
}
class HelloWorld {
// Function to delete the start node
public static Node deleteFromStart(Node head) {
head = head.next;
return head;
}
// Function to delete the given node
public static void deleteGivenNode(Node head, int val) {
if (head.data == val) {
head = head.next;
}
Node temp = head, prev = null;
while (temp.data != val) {
prev = temp;
temp = temp.next;
}
prev.next = temp.next;
}
// Function to delete the last node
public static void deleteFromEnd(Node head) {
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
// Function to print the list
public static void printList(Node head) {
Node temp = head;
while (temp != null) {
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
static void Main() {
Node head = new Node(10);
Node second = new Node(20);
Node third = new Node(30);
Node fourth = new Node(40);
head.next = second;
second.next = third;
third.next = fourth;
Console.Write("Original list: ");
printList(head);
head = deleteFromStart(head);
Console.Write("List after deleting the starting node: ");
printList(head);
deleteFromEnd(head);
Console.Write("List after deleting the ending node: ");
printList(head);
deleteGivenNode(head, 30);
Console.Write("List after deleting the given node: ");
printList(head);
}
}
// The code is contributed by Nidhi goel
JavaScript
<script>
// javascript code to implement the approach
// Creating a class Node
class Node {
constructor(val){
this.data = val;
this.next = null;
}
}
// Function to delete the start node
function deleteFromStart(head)
{
head = head.next;
return head;
}
// Function to delete the middle node
function deleteGivenNode(head, val)
{
if (head.data == val) {
head = head.next;
}
let temp = head;
let prev = null;
while (temp.data != val) {
prev = temp;
temp = temp.next;
}
prev.next = temp.next;
}
// Function to delete the last node
function deleteFromEnd(head)
{
let temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
// Function to print the list
function printList(head)
{
let temp = head;
while (temp != null) {
document.write(temp.data + " ");
temp = temp.next;
}
document.write("\n");
}
// Driver Code
let head = new Node(10);
let second = new Node(20);
let third = new Node(30);
let fourth = new Node(40);
head.next = second;
second.next = third;
third.next = fourth;
document.write("Original list: ");
printList(head);
head = deleteFromStart(head);
document.write("List after deleting the starting node: ");
printList(head);
deleteFromEnd(head);
document.write("List after deleting the ending node: ");
printList(head);
deleteGivenNode(head, 30);
document.write("List after deleting the given node: ");
printList(head);
// The code is contributed by Nidhi goel.
</script>
OutputOriginal list: 10 20 30 40
List after deleting the starting node: 20 30 40
List after deleting the ending node: 20 30
List after deleting the given node: 20
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read