在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;
}
链表的使用可以灵活地插入、删除和修改节点,相比数组具有更好的动态性能。但是链表的缺点是访问节点需要通过指针遍历,相对较慢,并且需要额外的内存来存储指针。