How do you define a singly linked list node structure in C?
A singly linked list node is a self-referential structure containing data and a pointer to the next node. The struct Node uses a pointer to its own type to create the chain.
Key design decisions:
- Use
typedefto avoid writingstruct Nodeeverywhere - The
nextpointer isNULLfor the last node in the list - You must use
struct Node *nextinside the definition (not the typedef alias) because the typedef is not yet complete
Memory layout: Each node occupies sizeof(int) + sizeof(pointer) bytes, typically 8 or 12 bytes on 32-bit systems, 12 or 16 bytes on 64-bit systems due to alignment/padding.
Define struct Node:
int data
pointer to struct Node -> next
Create node:
Allocate memory for one Node
Set data = value
Set next = NULL
Return pointer to node
#include <stdio.h>
#include <stdlib.h>
/* Self-referential structure for singly linked list */
typedef struct Node {
int data;
struct Node *next; /* pointer to next node */
} Node;
/* Factory function to create a new node */
Node *createNode(int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
int main(void) {
Node *head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
/* Traverse and print */
Node *curr = head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("NULL\n"); /* Output: 10 -> 20 -> 30 -> NULL */
/* Free all nodes */
curr = head;
while (curr != NULL) {
Node *temp = curr;
curr = curr->next;
free(temp);
}
return 0;
}
- •Self-referential struct: contains a pointer to its own type
- •Use struct Node *next inside the definition, not the typedef alias
- •Always check malloc return value for NULL
- •Last node's next pointer is NULL (sentinel for end of list)
- •sizeof(Node) includes padding for alignment
- •Cannot use the typedef name inside the struct definition itself -- use struct Node *next, not Node *next
- •Forgetting to set next = NULL in createNode leads to undefined behavior when traversing
- •Forgetting to check malloc return can cause NULL pointer dereference
- •sizeof(Node) may be larger than sizeof(int) + sizeof(Node*) due to struct padding