#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node{
int num;
struct node *next;
};
struct node *Create()
{
struct node *head,*p,*q;
int x,i=2;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
q=head;
printf("请输入第1个学生的成绩:");
scanf("%d",&x);
while(x!=-1)
{
p=(struct node *)malloc(sizeof(struct node));
p->num=x;
q->next=p;
q=p;
printf("请输入第%d个学生的成绩:",i);
scanf("%d",&x);
i++;
}
q->next=NULL;
return head;
}
struct node *Getk(struct node *head,int k)
{
struct node *p=head->next;
int s=1,q;
while(p&&s<k)
{
p=p->next; s++;
}
if(s==k) return p;
else return NULL;
}
struct node *Insert(struct node *head,int Index,int i)
{
struct node *p,*s;
p=Getk(head,Index-1);
s=(struct node *)malloc(sizeof(struct node));
s->num=i;
s->next=p->next;
p->next=s;
return head;
}
struct node *Delete(struct node *head,int Loc)
{
struct node *w,*c;
w=Getk(head,Loc-1);
c=w->next;
w->next=c->next;
free(c);
return head;
}
void Print(struct node *head)
{
struct node *L;
L=head->next;
int Index=1;
while(L!=NULL)
{
printf("第%d个学生的成绩是%d\n",Index,L->num);
L=L->next;
Index++;
}
}
void main()
{
struct node *phead,*x1;
int l,s;
phead=Create();
Print(phead);
printf("想要查找哪个结点:");
scanf("%d",&l);
x1=Getk(phead,l);
printf("第%d个同学的成绩是%d\n",l,x1->num);
int y,loc;
printf("请输入要增加的结点位置:");
scanf("%d",&y);
printf("请输入成绩大小:");
scanf("%d",&loc);
Insert(phead,y,loc);
Print(phead);
int o;
printf("请输入要删除的结点位置:");
scanf("%d",&o);
Delete(phead,o);
Print(phead);
}
单链表的创建,查找,插入,删除操作
最新推荐文章于 2023-01-13 15:23:26 发布