在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(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int data, int position) {
Node* newNode = createNode(data);
if (position == 0) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Position out of range\n");
exit(1);
}
newNode->next = current->next;
current->next = newNode;
}
}
void deleteNode(Node** head, int data) {
if (*head == NULL) {
printf("List is empty\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 not found\n");
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* next = current->next;
free(current);
current = next;
}
}
通過以上方法,可以簡化C語言鏈表操作的代碼結構。在實際應用中,還可以根據需要添加更多功能,例如查找節點、反轉鏈表等。