用C语言写一个单链表,包括创建链表,查找,删除,插入
时间: 2023-05-15 11:04:39 浏览: 110
以下是用 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;
}
// 查找节点
Node *findNode(Node *head, int value) {
Node *p = head;
while (p != NULL && p->data != value) {
p = p->next;
}
return p;
}
// 删除节点
Node *deleteNode(Node *head, int value) {
Node *p = head, *prev = NULL;
while (p != NULL && p->data != value) {
prev = p;
p = p->next;
}
if (p == NULL) {
printf("未找到要删除的节点\n");
return head;
}
if (prev == NULL) {
head = p->next;
} else {
prev->next = p->next;
}
free(p);
printf("已删除节点:%d\n", value);
return head;
}
// 插入节点
Node *insertNode(Node *head, int value, int position) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = value;
node->next = NULL;
if (position == 1) {
node->next = head;
head = node;
} else {
Node *p = head;
for (int i = 1; i < position - 1 && p != NULL; i++) {
p = p->next;
}
if (p == NULL) {
printf("插入位置无效\n");
} else {
node->next = p->next;
p->next = node;
}
}
return head;
}
// 打印链表
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("请输入链表长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("创建的链表为:");
printList(head);
int value, position;
printf("请输入要查找的节点的值:");
scanf("%d", &value);
Node *node = findNode(head, value);
if (node == NULL) {
printf("未找到节点\n");
} else {
printf("已找到节点:%d\n", node->data);
}
printf("请输入要删除的节点的值:");
scanf("%d", &value);
head = deleteNode(head, value);
printf("删除节点后的链表为:");
printList(head);
printf("请输入要插入的节点的值和位置:");
scanf("%d %d", &value, &position);
head = insertNode(head, value, position);
printf("插入节点后的链表为:");
printList(head);
return 0;
}
```
如果您有任何问题或建议,请随时告诉我。
阅读全文