How to Create Linked List Using Structure in C: Simple Guide
To create a linked list in C, define a
struct with data and a pointer to the next node. Then, dynamically allocate nodes and link them by setting the pointer to the next node's address.Syntax
A linked list node is created using a struct that contains two parts: the data and a pointer to the next node. The pointer connects nodes to form the list.
- struct Node: Defines the node structure.
- data: Holds the value (e.g., int).
- next: Pointer to the next node in the list.
c
struct Node {
int data;
struct Node* next;
};Example
This example creates a linked list with three nodes, assigns values, and prints them in order.
c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// Allocate memory for nodes
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
// Assign data and link nodes
head->data = 10;
head->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = NULL;
// Print linked list
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// Free memory
free(third);
free(second);
free(head);
return 0;
}Output
10 20 30
Common Pitfalls
Common mistakes when creating linked lists include:
- Not allocating memory with
malloc, causing crashes. - Forgetting to set the last node's
nextpointer toNULL, leading to undefined behavior. - Not freeing allocated memory, causing memory leaks.
- Mixing up
->and.operators when accessing struct members through pointers.
c
/* Wrong: Missing malloc causes crash */ struct Node* node; // node->data = 5; // Error: node is not allocated /* Right: Allocate before use */ node = (struct Node*)malloc(sizeof(struct Node)); node->data = 5; node->next = NULL;
Quick Reference
Remember these key points when working with linked lists in C:
- Define a
structwith data and a pointer to the next node. - Use
mallocto create nodes dynamically. - Link nodes by setting the
nextpointer. - Set the last node's
nexttoNULL. - Free allocated memory after use to avoid leaks.
Key Takeaways
Define a struct with data and a pointer to the next node to create linked list nodes.
Always allocate memory for nodes using malloc before using them.
Link nodes by setting the next pointer to the following node's address.
Set the last node's next pointer to NULL to mark the list end.
Free all allocated memory to prevent memory leaks.