您的位置:首页 > 其它

链表的创建,输出,删除,插入操作。VS2012环境下可执行

2016-01-25 09:56 507 查看
需求:定义学生结构体,包含学号和得分两个属性。包含建立学生链表,输出链表,删除指定学号的学生,插入某个学生,这些操作。

定义结构体:

struct student

{
long num;
float score;
struct student *next;

};

定义函数:createstu,del,insertstu,printstu。

具体实现:

#include <stdio.h>
#include <malloc.h>
#pragma warning(disable:4996)//

#define NULL 0

struct student
{
long num;
float score;
struct student *next;
};

#define LEN sizeof(struct student)

int n;

struct student * create()
{
struct student *head;
struct student *p1;
struct student *p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}

void printstu(struct student * head)
{
struct student *p;
p=head;
if(p==NULL)printf("it is NULL!\n");
while(p!=NULL)
{
printf("%ld,%5.1f\n",p->num,p->score);
p=p->next;
}
}

struct student *del(struct student * head,long num)
{
struct student *pre,*p;

pre=p=head;
while((p->num!=num)&&(p!=NULL))
{
pre=p;p=p->next;
}

if(num==p->num)
{
if(p==head){
head=p->next;
free(pre);}
else
{
pre->next=p->next;
free(p);
p=pre->next;
}
n--;
}
else printf("it is not been found\n");
return head;
}

struct student *insertstu(struct student *head,struct student *stu)
{
struct student *pre,*p;
pre=p=head;
while((p!=NULL)&&p->num<stu->num)
{
pre=p;p=p->next;
}
//insert it between pre and p
if(p!=head)//insert the list
{
stu->next=p;
pre->next=stu;
}
else
{
stu->next=head;
head=stu;
}
return head;
}
void main(int argc,char *argv[])
{
struct student *head;
struct student *stu;
head = create();

printstu(head);
printf("\n delete the num 100:\n");
head = del(head,100);
printstu(head);
printf("\n insert the num 100\n");
stu=(struct student *)malloc(LEN);
stu->num=100;
stu->score=100;
stu->next=NULL;

head =insertstu(head,stu );
printstu(head);

printf("\n del the num 103:\n");
head=del(head,103);
printstu(head);
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: