### Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

### Problem Statement

In this question, we are given a singly linked list and a position. We have to delete the node present at the given position.

### Problem Statement Understanding

Letβs first understand the problem statement with help of an example.

Suppose the linked list is 1 β 5 β 2 β 7 and the position given is 2. So, we have to delete the node present at the 2nd position.

**Note :** We are using 0 based indexing in this problem.

Here, in the given linked list, the node present at the 2^{nd} position is 2. So, we have to delete 2 from the given list. Final linked list after deleting 2 will be: 1 β 5 β 7

**Input :**

**Output :**

**Explanation :** The node at the 2nd position has been deleted.

How should we approach this problem? What is the first thing that comes to mind? Try to reach the position, right?

Yes, But with a little change.

To delete a node, we should also have the pointer to its previous node. We can tackle this by traversing till the (position – 1)^{th} node.

Let us have a glance at the approach.

### Approach

First, let’s think in terms of linked list what deleting a node means.

Let the linked list be:

1 β 5 β 2 β 7.

So, here, if we delete the node (2), we get :

1 β 5 β 7.

So, by deleting the node(2) we are making a connection between node(1) and node(5). That means the next of node(1) point to node(5).

**Observation**

- If we take some more examples, we will notice that we need to access the previous and the next node of the node that we need to delete.

Say, if the node to be deleted is target, and its previous node is prev and its next node is next1. So, to do the deletion of target node from the linked list, we need to perform the following operations:

1) prev β next = next1.

2) And finally free the target node.

By doing this, we are removing the target node at the given position and changing the necessary links.

There are a few corner cases. Try to think them out by taking a few examples. Everything is discussed in detail in the algorithm section.

### Algorithm

- If the head is NULL, return.
- Create a node temp and make it point to the head.
- If the position is 0, it means that we have to delete the head of the list. We can easily do that by head = temp β next and free(temp). As temp was pointing to the head, we have incremented the head and freed temp.
- If the position is not 0, we will proceed. Now, we will write a loop with i = 0 to i < (position -1). As we have discussed, to delete a node, we need a pointer to its previous node. So while traversing the loop, we will increment temp.
- Now, after the loop ends, if the temp is NULL or temp β next is NULL, we will simply return as the position is more than the number of nodes in the linked list.
- If the above condition fails, we will have temp pointing to the (position – 1)th node. Now, we simply have to change the required pointers.
- We will save the temp β next β next in a new node next1. Now, we will free temp β next, as it is the node at the given position. In the end, temp β next = next1. – In this way, there is no unnecessary memory leak and the node at the given position is getting deleted successfully.

### Dry Run

### Code Implementation

#include<stdio.h> #include<stdlib.h> void insert(int ); void display_List(); void delete(int ); struct node // Structure declaration { int data; struct node *next; // Self referral pointer }*head=NULL,*tail=NULL; // Initial value of Head and Tail pointer is NULL void delete(int pos) { struct node *temp = head; // Creating a temporary variable pointing to head int i; if(pos==0) { printf("\nElement deleted is : %d\n",temp->data); head=head->next; // Advancing the head pointer temp->next=NULL; free(temp); // Node is deleted } else { for(i=0;i<pos-1;i++) {="" temp="temp-">next; } // Now temp pointer points to the previous node of the node to be deleted struct node *del =temp->next; // del pointer points to the node to be deleted temp->next=temp->next->next; printf("\nElement deleted is : %d\n",del->data); del->next=NULL; free(del); // Node is deleted } printf("\nUpdated Linked List is : \n"); display_List(); return ; } void insert(int value) { struct node *newnode; // Creating a new node newnode = (struct node *)malloc(sizeof(struct node)); // Allocating dynamic memory newnode->data = value; // Assigning value to newnode newnode->next = NULL; if(head==NULL) // Checking if List is empty { head = newnode; tail = newnode; } else // If not empty then... { tail->next=newnode; tail=newnode; // Updating the tail node with each insertion } return ; } void display_List() { struct node *temp; // Creating a temporary pointer to the structure temp=head; // temp points to head; while(temp!=NULL) { if(temp->next==NULL) { printf(" %d->NULL",temp->data); } else { printf(" %d->",temp->data); } temp=temp->next; // Traversing the List till end } printf("\n"); return ; } // --Driver Code-- int main() { insert(1); insert(2); insert(3); insert(4); insert(5); insert(6); printf("\n--Created Linked List--\n"); display_List(); printf("\nLinked List after deletion"); delete(2); // List indexing starts from 0 return 0; }

#include <iostream> using namespace std; class Node { public: int data; Node *next; }; void push(Node** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void deleteNode(Node **head_ref, int position) { if (*head_ref == NULL) return; Node* temp = *head_ref; if (position == 0) { *head_ref = temp->next; free(temp); return; } for(int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; if (temp == NULL || temp->next == NULL) return; Node *next1 = temp->next->next; free(temp->next); temp->next = next1; } void printList( Node *node) { while (node != NULL) { cout << node->data << " "; node = node->next; } } int main() { Node* head = NULL; push(&head, 7); push(&head, 2); push(&head, 5); push(&head, 1); cout << "Created Linked List: "; printList(head); deleteNode(&head, 2); cout << "\nLinked List after Deletion at position 2: "; printList(head); return 0; }

public class LinkedList { Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } void deleteNode(int position) { if (head == null) return; Node temp = head; if (position == 0) { head = temp.next; return; } for (int i=0; temp!=null && i<position-1; i++) temp = temp.next; if (temp == null || temp.next == null) return; Node next1 = temp.next.next; temp.next = next1; } public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data+" "); tnode = tnode.next; } } public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(7); llist.push(2); llist.push(5); llist.push(1); System.out.println("\nCreated Linked list is: "); llist.printList(); llist.deleteNode(2); System.out.println("\nLinked List after Deletion at position 2: "); llist.printList(); } }

class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def deleteNode(self, position): if self.head is None: return if position == 0: self.head = self.head.next return self.head index = 0 current = self.head prev = self.head temp = self.head while current is not None: if index == position: temp = current.next break prev = current current = current.next index += 1 prev.next = temp return prev def printList(self): temp = self.head while(temp): print (" %d " % (temp.data),end=" ") temp = temp.next llist = LinkedList() llist.push(7) llist.push(2) llist.push(5) llist.push(1) print ("Created Linked List: ") llist.printList() llist.deleteNode(2) print ("\nLinked List after Deletion at position 4: ") llist.printList()

### Output

Created Linked List: 1 5 2 7

Linked List after Deletion at position 2: 1 5 7

**Time Complexity:** O(n), as list traversal is needed.

[forminator_quiz id="4195"]

So, in this article, we have tried to explain the most efficient approach to delete a node at a given position. This is an important question when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.