继续
时间: 2024-02-17 21:01:32 浏览: 3
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void createList(struct Node **head) {
*head = (struct Node *)malloc(sizeof(struct Node));
(*head)->next = NULL;
printf("请输入20个整数:\n");
struct Node *p = *head;
for (int i = 1; i <= 20; i++) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &newNode->data);
newNode->next = NULL;
p->next = newNode;
p = newNode;
}
printf("单链表的结点值为:");
struct Node *q = (*head)->next;
while (q != NULL) {
printf("%d ", q->data);
q = q->next;
}
printf("\n");
}
void searchNode(struct Node *head) {
int x;
printf("请输入要查找的整数:");
scanf("%d", &x);
struct Node *p = head->next;
while (p != NULL) {
if (p->data == x) {
printf("找到了\n");
return;
}
p = p->next;
}
printf("找不到\n");
}
void insertNode(struct Node *head) {
int i, x;
printf("请输入要插入的位置和数值(用空格隔开):");
scanf("%d %d", &i, &x);
struct Node *p = head;
for (int j = 1; j < i && p != NULL; j++) {
p = p->next;
}
if (p == NULL) {
printf("插入位置不合法\n");
return;
}
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = p->next;
p->next = newNode;
printf("单链表的结点值为:");
struct Node *q = head->next;
while (q != NULL) {
printf("%d ", q->data);
q = q->next;
}
printf("\n");
}
void deleteNode(struct Node *head) {
int i;
printf("请输入要删除的位置:");
scanf("%d", &i);
struct Node *p = head;
for (int j = 1; j < i && p != NULL; j++) {
p = p->next;
}
if (p == NULL || p->next == NULL) {
printf("删除位置不合法\n");
return;
}
struct Node *q = p->next;
p->next = q->next;
free(q);
printf("单链表的结点值为:");
struct Node *r = head->next;
while (r != NULL) {
printf("%d ", r->data);
r = r->next;
}
printf("\n");
}
int main() {
struct Node *head = NULL;
createList(&head);
int choice;
do {
printf("请选择操作:\n");
printf("1. 查找结点\n");
printf("2. 插入结点\n");
printf("3. 删除结点\n");
printf("4. 退出程序\n");
scanf("%d", &choice);
switch (choice) {
case 1:
searchNode(head);
break;
case 2:
insertNode(head);
break;
case 3:
deleteNode(head);
break;
case 4:
break;
default:
printf("输入有误,请重新选择\n");
break;
}
} while (choice != 4);
return 0;
}
```
注意,这段代码中的单链表是带表头的,即第一个结点不存储数据,只作为头结点使用。同时,这段代码中的单链表是静态创建的,即在程序运行期间无法动态添加或删除结点,如果需要实现动态添加或删除结点,需要进行相应的修改。