链表的基本操作
链表的插入、删除、添加,按自己想法写的代码。。。逻辑不是很明晰。。。
#include<stdio.h>
struct student
{
int score;
int n;
struct student *next;
};
struct student *creatlist()
{
struct student *head,*p1,*p2;
head=NULL;
p1=p2=(struct student *)malloc(sizeof(struct student));
scanf("%d,%d",&p1->n,&p1->score);
head=p1;
while(p1->n!=0)
{
p1=(struct student*)malloc(sizeof(struct student));
p2->next=p1;
p2=p1;
scanf("%d,%d",&p1->n,&p1->score);
}
p2->next=NULL;
return head;
}
struct student *addlink(int num,int score,struct student *pp)
{
int nn=0;
struct student *p0,*p1,*p2,*pk;
p0=(struct student *)malloc(sizeof(struct student));
p0->n=num;
p0->score=score;
p1=pp;
p2=p1->next;
while(p0->n<p1->n || p0->n>p2->n)
{
if(nn==0 && p0->n<p1->n)
{
pk=p1;
p1=p0;
p0->next=pk;
return p1;
}
if(p2->next==NULL && p0->n>p2->n)
{
p2->next=p0;
p0->next=NULL;
break;
}
nn++;
p1=p2;
p2=p2->next;
}
if(p0->n>p1->n && p0->n<p2->n)
{
p1->next=p0;
p0->next=p2;
}
return pp;
}
void print(struct student *p)
{
do
{
printf("%d,%d\n",p->n,p->score);
p=p->next;
}while(p!=NULL);
}
struct student *del(struct student *head,int j)
{
struct student *p1,*p2;
p1=head;
p2=head->next;
while(p1->n!=j && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->n==j)
{
if(p1==head)
head=head->next;
else
p2->next=p1->next;
}
return head;
}
void main()
{
struct student *pp;
int n,j;
int jj;
int kk;
pp=creatlist();
printf("output is\n");
print(pp);
printf("start add\,please input the num\n");
fflush(stdout);
scanf("%d,%d",&jj,&kk);
printf("the num and score is %d %d\n",jj,kk);
pp=addlink(jj,kk,pp);
print(pp);
}