c语言 定义一个单链表并增加、删除、修改、查找一个节点 完整代码
时间: 2023-08-03 09:05:22 浏览: 35
好的,下面是完整的C语言代码,包括定义一个单链表并增加、删除、修改、查找一个节点的操作:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node* next;
};
struct Node* head = NULL;
void addNode(int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->value = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void removeNode(int val) {
struct Node* current = head;
struct Node* prev = NULL;
while (current != NULL) {
if (current->value == val) {
if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
void updateNode(int oldVal, int newVal) {
struct Node* current = head;
while (current != NULL) {
if (current->value == oldVal) {
current->value = newVal;
return;
}
current = current->next;
}
}
struct Node* findNode(int val) {
struct Node* current = head;
while (current != NULL) {
if (current->value == val) {
return current;
}
current = current->next;
}
return NULL;
}
int main() {
addNode(1);
addNode(2);
addNode(3);
addNode(4);
printf("Before remove: ");
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
removeNode(3);
printf("After remove: ");
current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
updateNode(2, 5);
printf("After update: ");
current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
struct Node* foundNode = findNode(4);
if (foundNode != NULL) {
printf("Found node: %d\n", foundNode->value);
} else {
printf("Node not found\n");
}
return 0;
}
```
希望这份代码能对您有所帮助!