Algorithm to Delete a Node in a Singly Linked List
Algorithm to Delete a Node in a Singly Linked List
Given a singly linked list, we need to delete a node based on its value.
Algorithm:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
};
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
temp = temp->next;
temp->next = newNode;
*head = temp->next;
free(temp);
return;
prev = temp;
temp = temp->next;
if (temp == NULL) {
return;
prev->next = temp->next;
free(temp);
temp = temp->next;
printf("NULL\n");
// Main function
int main() {
// Insert nodes
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
printList(head);
// Delete a node
deleteNode(&head, 20);
printList(head);
deleteNode(&head, 50);
deleteNode(&head, 10);
printList(head);
return 0;
Explanation
1. insertAtEnd
2. deleteNode
3. printList
4. Main Function
o Inserts nodes.
Complexity Analysis