请用c语言写一个整数单链表的建立、查找、插入、删除、输出程序(线性表的链式存储实现),表中不允许有重复数据,
时间: 2024-06-16 17:04:39 浏览: 110
用C语言实现单链表的创建和基本操作
5星 · 资源好评率100%
当然可以!下面是一个用C语言实现整数单链表的建立、查找、插入、删除和输出的程序:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createList() {
Node* head = NULL;
Node* tail = NULL;
int num;
printf("请输入整数数据(输入-1结束):\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 查找节点
Node* findNode(Node* head, int target) {
Node* current = head;
while (current != NULL) {
if (current->data == target) {
return current;
}
current = current->next;
}
return NULL;
}
// 插入节点
void insertNode(Node** head, int target, int newData) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = newData;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* targetNode = findNode(*head, target);
if (targetNode == NULL) {
printf("未找到目标节点,插入失败。\n");
free(newNode);
return;
}
newNode->next = targetNode->next;
targetNode->next = newNode;
}
printf("插入成功。\n");
}
// 删除节点
void deleteNode(Node** head, int target) {
if (*head == NULL) {
printf("链表为空,删除失败。\n");
return;
}
Node* targetNode = findNode(*head, target);
if (targetNode == NULL) {
printf("未找到目标节点,删除失败。\n");
return;
}
if (*head == targetNode) {
*head = targetNode->next;
} else {
Node* prevNode = *head;
while (prevNode->next != targetNode) {
prevNode = prevNode->next;
}
prevNode->next = targetNode->next;
}
free(targetNode);
printf("删除成功。\n");
}
// 输出链表
void printList(Node* head) {
if (head == NULL) {
printf("链表为空。\n");
return;
}
Node* current = head;
printf("链表数据为:");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = createList();
int choice;
int target, newData;
while (1) {
printf("\n请选择操作:\n");
printf("1. 查找节点\n");
printf("2. 插入节点\n");
printf("3. 删除节点\n");
printf("4. 输出链表\n");
printf("5. 退出\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入要查找的节点值:");
scanf("%d", &target);
if (findNode(head, target) != NULL) {
printf("找到了该节点。\n");
} else {
printf("未找到该节点。\n");
}
break;
case 2:
printf("请输入要插入的目标节点值和新节点值:");
scanf("%d %d", &target, &newData);
insertNode(&head, target, newData);
break;
case 3:
printf("请输入要删除的节点值:");
scanf("%d", &target);
deleteNode(&head, target);
break;
case 4:
printList(head);
break;
case 5:
printf("程序已退出。\n");
exit(0);
default:
printf("无效的选择,请重新输入。\n");
}
}
return 0;
}
```
希望以上代码能满足你的需求!
阅读全文