生成实现链表的增删查找 打印的c语言代码
时间: 2024-11-20 22:43:42 浏览: 17
链表是一种常见的数据结构,它通过节点链接的方式存储元素。以下是简单的 C 语言代码示例,展示了如何实现单向链表的插入、删除、查找以及打印操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 节点保存的数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表末尾
void insertNode(Node** head, int value) {
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 查找节点
Node* searchNode(Node* head, int value) {
Node* temp = head;
while (temp != NULL) {
if (temp->data == value) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// 删除节点
void deleteNode(Node** head, int value) {
if (*head == NULL) {
return;
}
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* prev = *head;
Node* curr = (*head)->next;
while (curr != NULL && curr->data != value) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
prev->next = curr->next;
free(curr);
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 插入操作
insertNode(&head, 10);
insertNode(&head, 20);
insertNode(&head, 30);
// 打印链表
printList(head); // 输出: 10 20 30
// 查找操作
Node* foundNode = searchNode(head, 20);
if (foundNode != NULL) {
printf("Found %d\n", foundNode->data); // 输出: Found 20
} else {
printf("Not found.\n");
}
// 删除操作
deleteNode(&head, 20);
printList(head); // 输出: 10 30
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)