Linked List
A linked list is a linear data structure consisting of a sequence of elements, where each element is a separate object called a node. Each node contains data and a reference (pointer) to the next node in the sequence. Linked lists offer dynamic memory allocation and flexibility compared to arrays, as they can grow and shrink in size dynamically.
Types of Linked Lists
Singly Linked List:
Doubly Linked List:
Circular Linked List:
Implementation
Linked lists are implemented using structures (or classes in object-oriented programming) to define the nodes and pointers.
typedef struct Node {
int data;
struct Node* next;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}
// Function to insert a node at the beginning of the linked list
void insertAtBeginning(Node** headRef, int value) {
Node* newNode = createNode(value);
if (newNode != NULL) {
newNode->next = *headRef;
*headRef = newNode;
}
}
// Other operations like insertAtEnd, insertAfter, deleteNode, etc., can be implemented similarly.typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
newNode->prev = NULL;
}
return newNode;
}
// Function to insert a node at the beginning of the linked list
void insertAtBeginning(Node** headRef, int value) {
Node* newNode = createNode(value);
if (newNode != NULL) {
newNode->next = *headRef;
if (*headRef != NULL)
(*headRef)->prev = newNode;
*headRef = newNode;
}
}
// Other operations like insertAtEnd, insertAfter, deleteNode, etc., can be implemented similarly.Operations
Common operations performed on linked lists include:
Advantages of Linked Lists
Disadvantages of Linked Lists
Applications of Linked Lists
Examples of Linked List Usage