在C語言中,鏈表是一種基本的數(shù)據(jù)結(jié)構(gòu),用于存儲一系列元素。為了簡化鏈表操作,可以采用以下方法:
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語言鏈表操作的代碼結(jié)構(gòu)。在實際應(yīng)用中,還可以根據(jù)需要添加更多功能,例如查找節(jié)點、反轉(zhuǎn)鏈表等。