Linked List Types
- Singly Linked List
- Doubly Linked List
- Circular Linked List
- Node Insertion
- Node Deletion
Code Implemantation
1. Node and List Structure
typedef struct ListNode {
int value;
struct ListNode* next;
} ListNode;
typedef struct LinkedList {
ListNode* first;
size_t count;
} LinkedList;
2. List Initialization
void initList(LinkedList* lst) {
lst->first = NULL;
lst->count = 0;
}
3. List Destruciton
void destroyList(LinkedList* lst) {
ListNode* current = lst->first;
while (current) {
ListNode* temp = current;
current = current->next;
free(temp);
}
lst->first = NULL;
lst->count = 0;
}
4. Node Insertion
void insertNode(LinkedList* lst, int pos, int val) {
if (pos < 0 || pos > lst->count) {
printf("Invalid position\n");
return;
}
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->value = val;
if (pos == 0) {
newNode->next = lst->first;
lst->first = newNode;
} else {
ListNode* prev = lst->first;
for (int i = 0; i < pos - 1; i++) {
prev = prev->next;
}
newNode->next = prev->next;
prev->next = newNode;
}
lst->count++;
}
5. Node Deletion
void removeNode(LinkedList* lst, int pos) {
if (pos < 0 || pos >= lst->count) {
printf("Invalid position\n");
return;
}
if (pos == 0) {
ListNode* temp = lst->first;
lst->first = lst->first->next;
free(temp);
} else {
ListNode* prev = lst->first;
for (int i = 0; i < pos - 1; i++) {
prev = prev->next;
}
ListNode* toDelete = prev->next;
prev->next = toDelete->next;
free(toDelete);
}
lst->count--;
}
6. Node Search
ListNode* findNode(LinkedList* lst, int val) {
ListNode* current = lst->first;
while (current) {
if (current->value == val) {
return current;
}
current = current->next;
}
return NULL;
}
7. Get Node by Position
ListNode* getNodeAt(LinkedList* lst, int pos) {
if (pos < 0 || pos >= lst->count) {
printf("Invalid position\n");
return NULL;
}
ListNode* current = lst->first;
for (int i = 0; i < pos; i++) {
current = current->next;
}
return current;
}
8. Modify Node Value
void updateNode(LinkedList* lst, int pos, int val) {
ListNode* target = getNodeAt(lst, pos);
if (target) {
target->value = val;
}
}
9. Print List
void printList(LinkedList* lst) {
ListNode* current = lst->first;
while (current) {
printf("%d ", current->value);
current = current->next;
}
printf("NULL\n");
}
10. Compleet Example
#include <stdio.h>
#include <stdlib.h>
int main() {
LinkedList myList;
initList(&myList);
insertNode(&myList, 0, 5);
insertNode(&myList, 1, 15);
insertNode(&myList, 2, 25);
printf("Initial list: ");
printList(&myList);
removeNode(&myList, 1);
updateNode(&myList, 0, 10);
printf("Modified list: ");
printList(&myList);
destroyList(&myList);
return 0;
}