A Linked List is a linear data structure where elements (called nodes) are stored non-contiguously. Each node contains data and a reference (or link) to the next node in the sequence. This structure is flexible, allowing dynamic memory allocation and efficient insertions and deletions.
function insertAtBeginning(head, value):
new_node = createNewNode(value)
new_node.next = head
head = new_node
return head
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertAtBeginning(struct Node* head, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = head;
head = new_node;
return head;
}
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
head = insertAtBeginning(head, 5);
head = insertAtBeginning(head, 10);
head = insertAtBeginning(head, 15);
printList(head);
return 0;
}
- Insertion at the beginning of the list: O(1) (constant time).
- Searching for a value: O(n) (linear time), where 'n' is the number of nodes.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!