B. newNode->data should be assigned after head update
C. newNode->next should be NULL instead of head
D. newNode is not allocated memory; fix by malloc(sizeof(Node))
Solution
Step 1: Check newNode initialization
newNode is declared but not allocated memory with malloc, so it points to garbage.
Step 2: Fix by allocating memory
Use newNode = malloc(sizeof(Node)) before accessing newNode->data or newNode->next.
Final Answer:
newNode is not allocated memory; fix by malloc(sizeof(Node)) -> Option D
Quick Check:
Always malloc before using newNode [OK]
Hint: Always allocate memory before using new node [OK]
Common Mistakes:
Using uninitialized pointer
Assigning data before allocation
Changing head before linking newNode
5. You want to push multiple values 5, 15, 25 onto an empty linked list using the push function below. After pushing, you want to print the list from head to tail. Which code snippet correctly performs this and prints the list?
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* head = NULL;
void push(int val) {
Node* newNode = malloc(sizeof(Node));
newNode->data = val;
newNode->next = head;
head = newNode;
}
// Your code here to push and print