在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语言链表操作的代码结构。在实际应用中,还可以根据需要添加更多功能,例如查找节点、反转链表等。