#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printList(struct Node* head) { while (head != NULL) { printf("%d -> ", head->data); head = head->next; } printf("NULL\n"); } struct Node* deleteAtBeginning(struct Node* head) { if (head == NULL) return NULL; struct Node* temp = head; head = head->next; free(temp); return head; } int main() { struct Node* head = malloc(sizeof(struct Node)); struct Node* second = malloc(sizeof(struct Node)); struct Node* third = malloc(sizeof(struct Node)); head->data = 10; head->next = second; second->data = 20; second->next = third; third->data = 30; third->next = NULL; head = deleteAtBeginning(head); printList(head); return 0; }
The function deleteAtBeginning removes the first node (which has data 10) and returns the new head pointing to the second node. So the list starts from 20 now.
Deleting the first node removes exactly one node from the list, so 5 - 1 = 4 nodes remain.
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* deleteAtBeginning(struct Node* head) { struct Node* temp = head; head = head->next; free(temp); return head; } int main() { struct Node* head = NULL; head = deleteAtBeginning(head); return 0; }
The function does not check if head is NULL before accessing head->next. This causes a segmentation fault when head is NULL.
struct Node* deleteAtBeginning(struct Node* head) {
// Choose the correct implementation
}Option B correctly checks if head is NULL before deleting. It saves the current head in temp, moves head to the next node, frees the old head, and returns the new head.
First deletion removes 5, list becomes 10 -> 15 -> 20 -> NULL.
Second deletion removes 10, list becomes 15 -> 20 -> NULL.
