用c写一个单链表创建,增删改查
时间: 2023-05-25 17:04:47 浏览: 95
用c语言实现链表增删改查
以下是使用C语言实现单链表的代码,包括创建、增加节点、删除节点和查找节点等功能:
```c
#include <stdio.h>
#include <stdlib.h>
//定义单链表节点的结构体
struct Node {
int data;
struct Node* next;
};
//单链表头节点
struct Node* head = NULL;
//创建新节点并添加到单链表尾部
void addNode(int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
return;
}
struct Node* current = head;
while(current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
//删除指定值的节点
void deleteNode(int keyData) {
struct Node* current = head;
struct Node* previous = NULL;
while(current != NULL && current->data != keyData) {
previous = current;
current = current->next;
}
if(current == NULL) {
printf("Node not found in the list!\n");
return;
}
if(current == head) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
}
//修改指定节点的值
void updateNode(int keyData, int newData) {
struct Node* current = head;
while(current != NULL && current->data != keyData) {
current = current->next;
}
if(current == NULL) {
printf("Node not found in the list!\n");
return;
}
current->data = newData;
}
//查找节点
struct Node* searchNode(int keyData) {
struct Node* current = head;
while(current != NULL && current->data != keyData) {
current = current->next;
}
if(current == NULL) {
printf("Node not found in the list!\n");
return NULL;
}
return current;
}
//输出单链表中的所有节点
void printList() {
struct Node* current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
//测试代码
addNode(2);
addNode(4);
addNode(6);
printList();
deleteNode(4);
printList();
updateNode(6, 8);
printList();
searchNode(6);
return 0;
}
```
阅读全文