在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語言操作鏈表時,需要注意內存分配、指針操作、遍歷和釋放內存等方面的問題。正確操作鏈表可以提高程序的效率和穩定性。