本文对C语言链表进行详细介绍,包括创建,输出,删除,插入;
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student
{
int num;
float score;
struct student *next;
};
int n=0; //设置计数器
//输入链表
struct student *creat()//此函数返回一个指向链表头的指针
{
struct student *head,*p1,*p2;//p1为新开辟的结点,p2为末尾结点
p1=p2=(struct student *)malloc(LEN);
printf("num & score\n");
scanf("%d %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf("num & score\n");
scanf("%d %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
//输出链表
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)/*若p不是空指针,则执行循环体*/
{
printf("%d,%.2f\n",p->num,p->score);
p=p->next;
}
}
//删除结点
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL){printf("\nllist null;\n");return(head);}
p1=head;<span style="white-space:pre"> </span>//从头开始找结点
while(num!=p1->num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next; //p1后移一个结点
}
if(p1->num==num) //找到了,p1指向要删除的结点
{
if(p1==head) head=p1->next;//删除的结点为头结点
else p2->next=p1->next; //删除的结点不是头结点,p2原指向的是删除结点的前一结点
printf("\ndelete %d succeed\n",num);
n=n-1;
}
else printf("can't find %d\n",num);
return head;
}
//插入结点
struct student *insert(struct student *head,int num)//插入结点stud
{
struct student *p0,*p1,*p2;
p1=head;
//p0=stud; //p0指向要插入的结点
p0=(struct student *)malloc(LEN);
p0->num=num;
printf("input score\n");
scanf("%f",&p0->score);
if(head==NULL)
{head=p0;p0->next=NULL;}
else
while(p0->num > p1->num &&p1->next!=NULL)//p0在p1之后,需使p1向后移
{
p2=p1;
p1->next=NULL;
}
if(p0->num <= p1->num) //p0在p1之前
{
if(head==p1) head=p0;//p0插到头结点之前
else p2->next=p0; //p0插到头结点之后p1之前
p0->next=p1; //连接结点
}
else
{p1->next=p0;p0->next=NULL;}//新结点为最大数,插在链表末尾,while时可能p1->next为空
n=n+1;
return head;
}
int main()
{
struct student *head;
int num,n;
while(1)
{
system("cls");
printf(" 1. new creat\n");
printf(" 2. print \n");
printf(" 3. delete \n");
printf(" 4. insert \n");
printf("your choose\n");
scanf("%d",&n);
switch(n)
{
case 1:
head=creat();//调用creat函数,返回链表首地址
system("pause");
break;
case 2:
print(head);
system("pause");
break;
case 3:
printf("input number\n");
scanf("%d",&num);
del(head,num);
system("pause");
break;
case 4:
printf("input number\n");
scanf("%d",&num);
head=insert(head,num);
print(head);
system("pause");
break;
default: printf("error\n");break;
}
}
}