给我一个c语言代码,要求完成以下实验:实验内容 建立单链表,并在单链表上实现插入、删除和查找操作。 实验要求 (1)根据输入的一系列整数,以0标志结束,用头插法建立单链表,并输出单链表中各元素值,观察输入的内容与输出的内容是否一致。 (2)在单链表的第i个元素之前插入一个值为x的元素,并输出插入后的单链表中各元素值。 (3)删除单链表中第i个元素,并输出删除后的单链表中各元素值。 (4)在单链表中查找第i个元素,如果查找成功,则显示该元素的值,否则显示该元素不存在。
时间: 2023-05-31 20:07:19 浏览: 200
以下是C语言代码:
#include <stdio.h>
#include <stdlib.h>
//定义节点类型
typedef struct node {
int data;
struct node *next;
} Node;
//创建节点函数
Node *createNode(int data) {
Node *p = (Node *) malloc(sizeof(Node));
p->data = data;
p->next = NULL;
return p;
}
//创建链表函数
void createList(Node **head) {
int data = 0;
Node *p = NULL;
*head = NULL;
printf("输入一系列整数, 以 0 结束:\n");
scanf("%d", &data);
while (data != 0) {
p = createNode(data);
p->next = *head;
*head = p;
scanf("%d", &data);
}
printf("链表中各元素值:");
for (p = *head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
}
//插入函数,插入值为x的元素到第i个位置
void insert(Node **head, int x, int i) {
Node *p = *head, *q = NULL;
int j = 1;
while (p != NULL && j < i) {
q = p;
p = p->next;
j++;
}
if (p == NULL) {
printf("插入位置不合法!\n");
return;
}
Node *s = createNode(x);
s->next = p;
if (q == NULL) {
*head = s;
} else {
q->next = s;
}
printf("插入后的单链表中各元素值:");
for (p = *head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
}
//删除函数,删除第i个元素
void delete(Node **head, int i) {
Node *p = *head, *q = NULL;
int j = 1;
while (p != NULL && j < i) {
q = p;
p = p->next;
j++;
}
if (p == NULL) {
printf("删除位置不合法!\n");
return;
}
if (q == NULL) {
*head = p->next;
} else {
q->next = p->next;
}
free(p);
printf("删除后的单链表中各元素值:");
for (p = *head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
}
//查找函数,查找第i个元素
void find(Node *head, int i) {
Node *p = head;
int j = 1;
while (p != NULL && j < i) {
p = p->next;
j++;
}
if (p == NULL) {
printf("该元素不存在!\n");
} else {
printf("第%d个元素的值为:%d\n", i, p->data);
}
}
int main() {
Node *head = NULL;
createList(&head);
int x = 0, i = 0, choice = 0;
while (1) {
printf("请选择要进行的操作:\n");
printf("1.插入\n2.删除\n3.查找\n4.退出\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("在第几个位置前插入:");
scanf("%d", &i);
printf("插入的值是什么:");
scanf("%d", &x);
insert(&head, x, i);
break;
case 2:
printf("删除第几个元素:");
scanf("%d", &i);
delete(&head, i);
break;
case 3:
printf("查找第几个元素:");
scanf("%d", &i);
find(head, i);
break;
case 4:
exit(0);
default:
printf("无效的输入!\n");
break;
}
}
}
阅读全文
相关推荐


















