首先是链表的创建和遍历:
#include<stdio.h>
#include<stdlib.h>
struct student{
char name[20];
int number;
struct student *next;
};
int icount;
struct student *creat(){
struct student *phead=NULL;
struct student *pend,*pnew;
icount=0;
pend=pnew=(struct student *)malloc(sizeof(struct student));
printf("请输入学生的姓名和学号:\n");
scanf("%s",pnew->name);
scanf("%d",&pnew->number);
while(pnew->number!=0){
icount++;
if(icount==1){
pnew->next=phead;
pend=pnew;
phead=pnew;
}
else
{
pnew->next=NULL;
pend->next=pnew;
pend=pnew;
}
pnew=(struct student *)malloc(sizeof(struct student));
scanf("%s",pnew->name);
scanf("%d",&pnew->number);
}
free(pnew);
return phead;
}
void print(struct student *phead){
struct student *ptemp;
int i=1;
printf("***本名单有%d个学生***\n",icount);
ptemp=phead;
while(ptemp!=NULL){
printf("第%d个学生是:\n",i);
printf("姓名:%s\n",ptemp->name);
printf("学号:%d\n",ptemp->number);
ptemp=ptemp->next;
i++;
}
};
int main()
{
struct student *phead;
phead=creat();
print(phead);
}
然后是链表的插入:
#include<stdio.h>
#include<stdlib.h>
struct student{
char name[20];
int number;
struct student *next;
};
int icount;
struct student *creat(){
struct student *phead=NULL;
struct student *pend,*pnew;
icount=0;
pend=pnew=(struct student *)malloc(sizeof(struct student));
printf("请输入学生的姓名和学号:\n");
scanf("%s",pnew->name);
scanf("%d",&pnew->number);
while(pnew->number!=0){
icount++;
if(icount==1){
pnew->next=phead;
pend=pnew;
phead=pnew;
}
else
{
pnew->next=NULL;
pend->next=pnew;
pend=pnew;
}
pnew=(struct student *)malloc(sizeof(struct student));
scanf("%s",pnew->name);
scanf("%d",&pnew->number);
}
free(pnew);
return phead;
}
void print(struct student *phead){
struct student *ptemp;
int i=1;
printf("***本名单有%d个学生***\n",icount);
ptemp=phead;
while(ptemp!=NULL){
printf("第%d个学生是:\n",i);
printf("姓名:%s\n",ptemp->name);
printf("学号:%d\n",ptemp->number);
ptemp=ptemp->next;
i++;
}
};
struct student *insert(struct student *phead, int inumber)
{
struct student *p=phead,*pnew;
while(p&&p->number!=inumber)
p=p->next;
printf("请输入学生的姓名和学号:\n");
pnew=(struct student *)malloc(sizeof(struct student));
scanf("%s",pnew->name);
scanf("%d",&pnew->number);
pnew->next=p->next;
p->next=pnew;
icount++;
return phead;
}
int main()
{
struct student *phead;
phead=creat();
phead=insert(phead,6);
print(phead);
}
接下来是链表的删除:
简单拿出来删除的一小段代码:
void delete(struct student *phead, int a)
{
int i;
struct student *ptemp;
struct student *ppre;
ptemp=phead;
ppre=ptemp;
printf("------删除第%d个学生-------",a);
for(i=1;i<a;i++){
ppre=ptemp;
ptemp=ptemp->next;
}
ppre->next=ptemp->next;
free(ptemp);
icount--;
}
下来是自主思考的查找:
void lookfor(struct student *p,int a){
struct student *m,*n;
int i;
m=p;
for(i=1;i<=a;i++){
n=m;
m=m->next;
if(i==a){
printf("kaishile\n");
printf("%s\n",n->name);
printf("%d\n",n->number);
break;
}
}
}
链表相关的替换:
void change(struct student *p,int a){
struct student *m,*n;
int i;
m=p;
for(i=1;i<=a;i++){
n=m;
m=m->next;
if(i==a){
printf("kaishile\n");
scanf("%s",n->name);
scanf("%d",&n->number);
break;
}
}
}