Overview
A singly linked list is a linear data structure where each element (node) contains data and a pointer to the next node in the sequence. This implementation stores strings with their lengths.Data Structure Definition
The singly linked list node is defined inlists.h:16-21:
lists.h
Each node contains:
str: A dynamically allocated string (must be freed)len: The length of the stringnext: Pointer to the next node (NULL if last node)
Core Operations
Traversal and Counting
Space Complexity: O(1) - only counter variable needed
Insertion Operations
Performance Comparison:
add_node(): O(1) - inserts at beginningadd_node_end(): O(n) - must traverse to end
Memory Management
free_list.c
Important: Always free the string (
str) before freeing the node itself to avoid memory leaks. Each node requires two free() calls.Usage Example
example.c
Complexity Summary
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Insert at beginning | O(1) | O(1) |
| Insert at end | O(n) | O(1) |
| Traverse/Print | O(n) | O(1) |
| Search | O(n) | O(1) |
| Delete | O(n) | O(1) |
Key Characteristics
- Unidirectional: Can only traverse forward
- Dynamic size: Grows and shrinks as needed
- No random access: Must traverse from head to reach any element
- Memory efficient: Only stores pointer to next node
- String management: Uses
strdup()for string duplication and requires explicit freeing