c语言实验十五链表
链表的插入 查询 删除,
不会吧,来看看月腾兄的;
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
//向链表指定位置插入数据
int insert(struct node *L, int i, int *e)
{
struct node *p, *s;
p = L;
int j = 0;
while (p&&j<i-1)
{
p = p->next;
++j;
}
if (!p || j > i - 1)return 0;
s= (struct node*)malloc(sizeof(struct node));
s->data = *e;
s->next = p->next;
p->next = s;
return 1;
}
//创建链表
void Create(struct node *L, int n)
{
int i;
int v;
struct node *p;
L->next = NULL;
//循环录入数据
for (i = n; i > 0; --i)
{
p = (struct node *) malloc(sizeof(struct node));
scanf_s("%d", &v);
p->data = v;
p->next = L->next; //头插法
L->next = p;
}
}
//输出链表中的数据
int Print(struct node *L, char* s) {
struct node *p;
printf("%s", s);
p = L->next;
if (p == NULL)
{
printf("链表为空\n");
return 0;
}
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 1;
}
//删除链表中指定位置的数据
int Delete(struct node *L, int i, int *e)
{
struct node *p, *q;
p = L;
int j = 0;
while (p->next && j < i - 1)
{
p = p->next;
++j;
}
if (!(p->next) || j > i - 1) return 0;
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return 1;
}
//获取链表中指定位置的数据
int find(struct node *L, int i, int *e)
{
//L为带头结点的单链表的头指针。当第i个元素存在时,其赋值给e并返回1,否则返回0
struct node *p;
p = L->next;
int j = 1;
while (p&&j < i)
{
p = p->next;
++j;
}
if (!p || j > i) return 0;
*e = p->data;
return 1;
}
void main()
{
struct node L;
printf("请输入3个初始数据");
Create(&L, 3);
Print(&L,"初始化的链表");
//定义inser函数的参数,插入位置和数值
//插入功能演示
int s, v;
printf("请输入数据插入的位置s 和数值v :");
scanf_s("%d%d", &s, &v);
printf("%s", insert(&L, s, &v) ? "插入成功.\n" : "插入失败.\n");
Print(&L, "插入后的链表:");
//删除功能演示
printf("请输入数据删除的位置s :");
scanf_s("%d", &s);
if (Delete(&L, s, &v))
printf("删除成功.删除的数据是:%d\n", v);
else
printf("删除失败.位置有误.");
Print(&L, "删除后的链表:");
//查询功能演示
printf("请输入要查询的数据位置s :");
scanf_s("%d", &s);
find(&L, s, &v);
printf("第%d个数是:%d\n\n", s, v);
system("pause");
return 0;
}