用C语言写一个单链表,包括创建链表,打印链表,按址查找,按值查找,删除和删除所有,插入,并对每个操作进行验证
时间: 2023-05-15 18:04:51 浏览: 95
单链表.c(单链表,使用C语言编写,具有插入、删除、显示等功能)
4星 · 用户满意度95%
好的,以下是用C语言实现单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建链表
Node* createList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node*)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &node->data);
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 打印链表
void printList(Node *head) {
printf("链表的值为:");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 按址查找
Node* findByAddr(Node *head, int addr) {
while (head != NULL) {
if (head == (Node*)addr) {
return head;
}
head = head->next;
}
return NULL;
}
// 按值查找
Node* findByValue(Node *head, int value) {
while (head != NULL) {
if (head->data == value) {
return head;
}
head = head->next;
}
return NULL;
}
// 删除
void deleteNode(Node **head, Node *node) {
if (*head == node) {
*head = node->next;
} else {
Node *prev = *head;
while (prev->next != node) {
prev = prev->next;
}
prev->next = node->next;
}
free(node);
}
// 删除所有
void deleteAll(Node **head, int value) {
Node *prev = NULL, *curr = *head;
while (curr != NULL) {
if (curr->data == value) {
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
Node *temp = curr;
curr = curr->next;
free(temp);
} else {
prev = curr;
curr = curr->next;
}
}
}
// 插入
void insertNode(Node **head, int value, int pos) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = value;
node->next = NULL;
if (pos == 0) {
node->next = *head;
*head = node;
} else {
Node *prev = *head;
for (int i = 0; i < pos - 1; i++) {
prev = prev->next;
}
node->next = prev->next;
prev->next = node;
}
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printList(head);
int addr;
printf("请输入要查找的节点的地址:");
scanf("%d", &addr);
Node *node = findByAddr(head, addr);
if (node != NULL) {
printf("找到了节点,值为:%d\n", node->data);
} else {
printf("未找到节点!\n");
}
int value;
printf("请输入要查找的节点的值:");
scanf("%d", &value);
node = findByValue(head, value);
if (node != NULL) {
printf("找到了节点,地址为:%d\n", node);
} else {
printf("未找到节点!\n");
}
int pos;
printf("请输入要删除的节点的位置:");
scanf("%d", &pos);
deleteNode(&head, findByAddr(head, pos));
printList(head);
printf("请输入要删除的节点的值:");
scanf("%d", &value);
deleteAll(&head, value);
printList(head);
printf("请输入要插入的节点的值和位置:");
scanf("%d %d", &value, &pos);
insertNode(&head, value, pos);
printList(head);
return 0;
}
```
以上代码实现了单链表的创建、打印、按址查找、按值查找、删除、删除所有、插入等操作,并对每个操作进行了验证。
阅读全文