Linked List Data Structure in C

Linked lists in C are a data structure that uses pointers to create a dynamic, flexible list of elements. Each element, called a node, contains both data and a reference (pointer) to the next node in the list, allowing for efficient insertions and deletions.

Linked List in C

Linked lists are useful for applications where the size of the list is not known at compile time or where the elements of the list need to be inserted and deleted frequently.

#include <stdio.h> #include <stdlib.h> // Define a structure for a singly linked list node struct Node { int data; struct Node* next; }; // Function to create a new node struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { perror("Memory allocation failed"); exit(EXIT_FAILURE); } newNode->data = data; newNode->next = NULL; return newNode; } // Function to insert a node at the beginning of the list void insertAtBeginning(struct Node** head, int data) { struct Node* newNode = createNode(data); newNode->next = *head; *head = newNode; } // Function to print the linked list void printList(struct Node* head) { struct Node* current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); } int main() { struct Node* head = NULL; // Initialize an empty linked list insertAtBeginning(&head, 3); insertAtBeginning(&head, 2); insertAtBeginning(&head, 1); printf("Linked List: "); printList(head); return 0; }
//Output: Linked List: 1 -> 2 -> 3 -> NULL

In this example, we've created a singly linked list with three nodes containing data values 1, 2, and 3.

Here's a breakdown of the key components:

  1. struct Node defines the structure of a node in the linked list, consisting of an integer data and a pointer next to the next node in the list.
  2. createNode is a function to dynamically allocate memory for a new node and initialize its data and next pointer.
  3. insertAtBeginning inserts a new node at the beginning of the list. It updates the head pointer to point to the new node.
  4. printList traverses the linked list from the head and prints its elements, followed by "NULL" to indicate the end of the list.
  5. in main, we create an empty linked list (head is initially NULL) and insert three nodes at the beginning. Finally, we print the contents of the linked list.

Conclusion

Linked lists using pointers in C are a dynamic data structure where elements, known as nodes, are connected via pointers to form a chain-like structure. Each node holds data and a reference to the next node, allowing for efficient insertion and deletion operations, making linked lists versatile for managing data in C programs.