C Algorithm – Delete a Linked List node at a given position

C Algorithm - Delete a Linked List node at a given position - Linked List - Given a singly linked list and a position, delete a linked list

Given a singly linked list and a position, delete a linked list node at the given position.

Example:

```Input: position = 1, Linked List = 8->2->3->1->7

Input: position = 0, Linked List = 8->2->3->1->7

If node to be deleted is root, simply delete it. To delete a middle node, we must have pointer to the node previous to the node to be deleted. So if positions is not zero, we run a loop position-1 times and get pointer to the previous node.

C Programming:

``````// A complete working C program to delete a node in a linked list
// at a given position
#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *next;
};

/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data  = new_data;
}

/* Given a reference (pointer to pointer) to the head of a list
and a position, deletes the node at the given position */
void deleteNode(struct node **head_ref, int position)
{
// If linked list is empty
return;

// If head needs to be removed
if (position == 0)
{
return;
}

// Find previous node of the node to be deleted
for (int i=0; temp!=NULL && i<position-1; i++)
temp = temp->next;

// If position is more than number of ndoes
if (temp == NULL || temp->next == NULL)
return;

// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
struct node *next = temp->next->next;

free(temp->next);  // Free memory

temp->next = next;  // Unlink the deleted node from list
}

// This function prints contents of linked list starting from
// the given node
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}

/* Drier program to test above functions*/
int main()
{

puts("\nLinked List after Deletion at position 4: ");
return 0;
}``````

Output:

```Created Linked List:
8  2  3  1  7
Linked List after Deletion at position 4:
8  2  3  1```
READ  Cpp Algorithm - Write a function to delete a Linked List

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.