Delete a Linked List Node at a Given Position | C Program

Program in C

#include <stdio.h>
#include <stdlib.h>

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

int calcSize(struct Node* node){
int size=0;

while(node!=NULL){
node = node->next;
size++;
}
return size;
}

void insert(struct Node** head, int data){

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = data;
newNode->next = *head;

//changing the new head to this freshly entered node
*head = newNode;
}

void delete(struct Node** head, int pos)
{
struct Node* temp = *head;
struct Node* previous;

//if the head node itself needs to be deleted
int size = calcSize(*head);

if(pos<1 || pos>size){
printf("Enter valid position\n");

return;
}
if(pos==1)
{
//Case 1 head becomes 30
*head = temp->next; //changing head to next in the list
printf("Value %d, deleted \n",temp->data);

//case 1: 22 deleted and freed
free(temp);
return;
}

//run until we find the value to be deleted in the list
while (--pos)
{
//store previous link node as we need to change its next val
previous = temp;
temp = temp->next;
}

// Case 2: (24)->next = 16 (as 20->next = 16)
// Case 3: (16)->next = NULL (as 12->next = NULL)
previous->next = temp->next;
printf("Value %d, deleted \n",temp->data);

free(temp);
//case 2: 20 deleted and freed
//case 3: 12 deleted and freed
}

void display(struct Node* node){

//as linked list will end when Node is Null
while(node!=NULL)
{
printf("%d ",node->data);
node = node->next;
}
printf("\n\n");
}

int main()
{
struct Node* head = NULL;

/*Need & i.e. address as we
need to change head address only needs to traverse
and access items temporarily
*/
insert(&head,12);
insert(&head,16);
insert(&head,20);
insert(&head,24);
insert(&head,30);
insert(&head,22);

/*No need for & i.e. address as we do not
need to change head address
*/
display(head);

//deleting first occurance of a value in linked list
delete(&head,1);
display(head);

delete(&head,3);
display(head);

delete(&head,4);
display(head);

delete(&head,-2);
delete(&head,10);

return 0;
}