A linked list is a data structure in C that consists of a collection of nodes, each containing a data element and a reference (or pointer) to the next node in the list. The nodes are not necessarily stored in contiguous memory locations, as is the case with arrays. Instead, each node contains a pointer to the next node in the list, allowing the nodes to be stored in non-contiguous memory locations.
The basic structure of a linked list is as follows:
struct Node {
int data; // data element
struct Node* next; // pointer to next node
};
Each node contains a data element, which can be of any data type, and a pointer to the next node in the list. The last node in the list typically has a null pointer, indicating the end of the list.
Linked lists are often used in situations where the size of the data structure is not known in advance or where the data needs to be inserted or deleted frequently. Unlike arrays, linked lists can be dynamically resized by adding or removing nodes.
To traverse a linked list, you start at the head node and follow the pointers to each subsequent node until you reach the end of the list. Here is an example of a function that prints the contents of a linked list:
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
This function takes the head of the list as its argument and traverses the list, printing the data element of each node.
Linked lists can also be used to implement various data structures such as stacks, queues, and hash tables. However, linked lists have some drawbacks, such as increased memory usage due to the need to store pointers, and slower access time since elements are not stored in contiguous memory locations.