在C語言中,鏈表(LinkList)是一種常用的數據結構,用于存儲和組織數據。鏈表由一系列節點組成,每個節點包含一個數據元素和一個指向下一個節點的指針。鏈表的最后一個節點指向NULL,表示鏈表的結束。
鏈表的用法包括以下幾個方面:
struct Node {
int data;
struct Node* next;
};
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;
}
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
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;
}
鏈表的使用可以靈活地插入、刪除和修改節點,相比數組具有更好的動態性能。但是鏈表的缺點是訪問節點需要通過指針遍歷,相對較慢,并且需要額外的內存來存儲指針。