Delete a node at any position in a Linked List

Honey
2 min readNov 4, 2021

Objective : To delete a node at any given position in a Linked List.

Example :

INPUT

Linked list : 1 2 3 4 5

Enter the position of the value to be deleted : 3

OUTPUT

Linked List after deletion : 1 2 4 5

Visual Representation :

Linked List deletion : Node ‘c’ to be deleted at position 3

For this, we will need two pointers. One for iterating through the linked list and the other one for pointing the values and getting the address of the node next after the node to be deleted.

Two pointers namely p and ptr will be declared. Later, we will follow few steps which you’ll se listed below in brief.

  1. Make ptr point to head.
  2. Run a for loop.
  3. In the for loop, make ptr equal to p and move p one step forward like it is shown below. i.e. ptr=p and p = p->next .

4. Make sure to run the for loop run until i is less than the position to be deleted i.e. i<pos. By doing this, we will be able to access the address of the node next to the node to be deleted.

Because we know, the next of p should be equal to the next of ptr after we will delete the node at a position where p is currently pointing.

i.e. After node deletion at position 3, ptr->next = p->next

The for loop ends when i<pos

5. At the end we will free p using free(p)

Below is the complete function implemented using C++,

--

--

Honey

Tech or non-tech 'll post all my crazy cool stuff here!