在C語言中,鏈表是一種基本的數(shù)據(jù)結(jié)構(gòu),用于存儲一系列元素
typedef struct Node {
int data; // 數(shù)據(jù)域,用于存儲數(shù)據(jù)
struct Node* next; // 指針域,指向下一個節(jié)點(diǎn)
} 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* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void deleteNode(Node** head, int data) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
Node* temp = *head;
if (temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp->next != NULL && temp->next->data != data) {
temp = temp->next;
}
if (temp->next != NULL) {
Node* nextNode = temp->next->next;
free(temp->next);
temp->next = nextNode;
} else {
printf("Node not found\n");
}
}
void traverseList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
void freeList(Node* head) {
Node* temp = head;
while (temp != NULL) {
Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
}
遵循以上步驟,可以避免鏈表操作中的常見錯誤,如內(nèi)存泄漏、空指針解引用等。在實(shí)際編程過程中,還需要注意對鏈表節(jié)點(diǎn)的創(chuàng)建、插入、刪除等操作進(jìn)行適當(dāng)?shù)腻e誤處理,以確保程序的健壯性。