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.
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:
- 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.
- createNode is a function to dynamically allocate memory for a new node and initialize its data and next pointer.
- insertAtBeginning inserts a new node at the beginning of the list. It updates the head pointer to point to the new node.
- printList traverses the linked list from the head and prints its elements, followed by "NULL" to indicate the end of the list.
- 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.
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.