- 1、本文档共5页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
简单动态链表
制作一个包含N个学生学号和成绩的简单单向动态链表,并要求实现能对对该链表进行删除和插入的简单操作。
源代码:(编码环境VS2012)
#include stdafx.h
#includestdio.h
#includemalloc.h
#define NULL 0
struct student
{long num;
float score;
struct student *next;
};
int n;//n为结点数 全局变量
//创建链表
struct student *creat()
{
struct student *head=NULL,*p2,*p1;
n=0;
p2=p1=(struct student *)malloc(sizeof(struct student));//开辟一个新结点
scanf_s(%ld,%f,p1-num,p1-score);
while (p1-num!=0)
{ n++;//计数
if(n==1)head=p1;
else p2-next=p1;
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
scanf_s(%ld,%f,p1-num,p1-score);
}
p2-next=NULL;
return head;
};
//输出链表
void print(struct student *head)
{
struct student *p;
printf(\nThe %d records are:\n,n);
p=head;
if(head!=NULL)
do
{
printf(%ld%5.1f\n,p-num,p-score);
p=p-next;
} while (p!=NULL);
}
//删除结点
struct student *del(struct student *head,long num)
{
struct student *p1,*p2;
if(head==NULL)
{printf(\nlist null\n);
return head;}
p1=p2=head;
while(num!=p1-nump1-next!=NULL)//p1不是要删除的结点并且后面还有结点
{
p2=p1;
p1=p1-next;//p1指向下一个结点
}
if(num==p1-num)//p1是要删除的结点
{
if(p1==head)head=p1-next;//若p1为首结点则把第二个结点地址赋给head
else p2-next=p1-next; //否则将下一个结点的地址赋给前一个结点的地址
printf(delete:%d\n,num);
n=n-1;//结点数减1
}
else printf(Error);
return head;
}
//插入结点
struct student *insert(struct student *head,struct student *stud)
{
struct student *p0,*p1,*p2;
p1=p2=head;//p1 p1均指向首结点
p0=stud;//p0指向要插入的结点
if(head==NULL)//若为空表
{
head=p0;
p0-next=NULL;//p0指向的结点作为首结点
}
else
{
while((p0-nump1-num)(p1-next!=NULL))
{
p2=p1;//p2指向p1刚才指向的结点
p1=p1-next;//p1指向下一个结点
}
if(p0-num=p1-num)
{
if(head==p1)head=p0;//插到第一个结点前
else p2-next=p0-next;//插到p2指向的结点后
p0-next=p1-next;
}
else
{
p1-next=p0;
p0-next=NULL;//插到最后的结点后面
}
}
n=n+1;//结点数+1
return head;
}
//主函数
void main()
{
struct student *head,*stud;
long del_num;
printf(input records:\n);
head=creat();
print(head);
printf(\ninput the delete numb
文档评论(0)