在C语言中,链表是一种基本的数据结构,用于存储一系列元素。操作链表时需要注意以下几点:
typedef struct Node {
int data; // 数据域,用于存储数据
struct Node* next; // 指针域,用于指向下一个节点
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void deleteNode(Node** head, int data) {
if (*head == NULL) {
printf("List is empty, nothing to delete\n");
return;
}
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != data) {
current = current->next;
}
if (current->next == NULL) {
printf("Node with data %d not found\n", data);
return;
}
Node* temp = current->next;
current->next = current->next->next;
free(temp);
}
void traverseList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
void freeList(Node* head) {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
总之,在使用C语言操作链表时,需要注意内存分配、指针操作、遍历和释放内存等方面的问题。正确操作链表可以提高程序的效率和稳定性。