C语言实现结构体动态链表的增删改查
时间: 2024-04-06 11:27:01 浏览: 77
用c语言实现链表增删改查
C语言可以通过结构体和指针来实现动态链表的增删改查操作。下面是一个简单的示例代码:
首先,定义一个结构体表示链表的节点:
```c
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
接下来,定义一些基本的操作函数:
1. 创建一个新节点:
```c
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
```
2. 在链表末尾插入一个节点:
```c
void insertNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
```
3. 删除指定数值的节点:
```c
void deleteNode(Node** head, int data) {
if (*head == NULL) {
return;
}
Node* current = *head;
Node* prev = NULL;
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}
if (current == NULL) {
return;
}
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
```
4. 修改指定数值的节点:
```c
void modifyNode(Node* head, int oldData, int newData) {
Node* current = head;
while (current != NULL && current->data != oldData) {
current = current->next;
}
if (current != NULL) {
current->data = newData;
}
}
```
5. 查找指定数值的节点:
```c
Node* searchNode(Node* head, int data) {
Node* current = head;
while (current != NULL && current->data != data) {
current = current->next;
}
return current;
}
```
使用这些函数,你可以实现对动态链表的增删改查操作。
阅读全文