C linked lists
Created By: chatGPT
Linked lists are a fundamental data structure in C that enable dynamic memory allocation and efficient insertion and deletion of elements. Unlike arrays, linked lists do not have a fixed size, allowing them to grow and shrink as necessary. A linked list is composed of nodes, where each node contains data and a pointer to the next node in the sequence.
struct Node {
int data;
struct Node* next;
};
To create a new node, you need to allocate memory for it and set its data and next pointer. This is typically done using the malloc function from the stdlib.h library, which allocates a block of memory.
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
In a linked list, you need to keep track of the head of the list, which serves as the entry point for accessing the nodes. When you want to add a node, you can either insert it at the beginning, end, or at a specific position in the list.
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
To insert a node at the end of the linked list, you must traverse the list until you reach the last node, then link the new node to the end.
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
When dealing with linked lists, it's important to implement a function to free the allocated memory. This helps to prevent memory leaks in your program.
void freeList(struct Node* head) {
struct Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
Finally, always remember to test the linked list operations. Create a linked list and perform various operations such as inserting and traversing nodes to ensure everything works correctly.
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 10);
insertAtBeginning(&head, 20);
insertAtEnd(&head, 30);
freeList(head);
return 0;
}