What is the usage of linklist in C language?
In C language, a LinkList is a common data structure used to store and organize data. It consists of a series of nodes, each containing a data element and a pointer to the next node. The last node in the list points to NULL, indicating the end of the list.
The usage of linked lists includes several aspects:
- Define the structure for a linked list node: Representing a linked list node by defining a structure that contains a data element and a pointer to the next node.
struct Node {
int data;
struct Node* next;
};
- Creating a linked list: Using malloc function to dynamically allocate memory for creating linked list nodes, and using pointers to connect the nodes.
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
struct Node* addNode(struct Node* head, int data) {
struct Node* newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
return head;
}
- Traverse the linked list: Using a loop structure to iterate through all nodes in the linked list, pointers can be used to access each node’s data element one by one.
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
- Inserting and deleting nodes: Nodes can be inserted and deleted in a linked list, updating the pointer relationships between nodes.
struct Node* insertNode(struct Node* head, int data, int position) {
struct Node* newNode = createNode(data);
if (position == 1) {
newNode->next = head;
head = newNode;
} else {
struct Node* current = head;
for (int i = 1; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
}
}
return head;
}
struct Node* deleteNode(struct Node* head, int position) {
if (position == 1) {
struct Node* temp = head;
head = head->next;
free(temp);
} else {
struct Node* current = head;
struct Node* previous = NULL;
for (int i = 1; i < position && current != NULL; i++) {
previous = current;
current = current->next;
}
if (current != NULL) {
previous->next = current->next;
free(current);
}
}
return head;
}
The use of linked lists allows for flexible insertion, deletion, and modification of nodes compared to arrays, with better dynamic performance. However, a disadvantage of linked lists is that accessing nodes requires traversing through pointers, making it relatively slower, and requiring additional memory to store pointers.