用c语言编写单链表的增删改查
时间: 2023-03-31 19:03:42 浏览: 119
可以使用结构体来实现单链表,每个结构体包含一个数据域和一个指向下一个结构体的指针。具体实现如下:
1. 增加节点:
首先定义一个结构体:
struct Node {
int data;
struct Node* next;
};
然后定义一个头节点:
struct Node* head = NULL;
接着,可以编写一个函数来增加节点:
void addNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
2. 删除节点:
可以编写一个函数来删除节点:
void deleteNode(int data) {
struct Node* current = head;
struct Node* previous = NULL;
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
}
if (current == NULL) {
return;
}
if (previous == NULL) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
}
3. 修改节点:
可以编写一个函数来修改节点:
void modifyNode(int oldData, int newData) {
struct Node* current = head;
while (current != NULL && current->data != oldData) {
current = current->next;
}
if (current == NULL) {
return;
}
current->data = newData;
}
4. 查找节点:
可以编写一个函数来查找节点:
void searchNode(int data) {
struct Node* current = head;
while (current != NULL && current->data != data) {
current = current->next;
}
if (current == NULL) {
printf("节点不存在\n");
} else {
printf("节点存在,数据为:%d\n", current->data);
}
}
以上就是用 C 语言编写单链表的增删改查的方法。
阅读全文