单向链表的基本操作:
包括建立单向链表,打印,删除,插入(查找操作包含在删除和插入中)。
#include <iostream>
#include<cstdio>#include<cstdlib>
using namespace std;
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
long num;
float score;//值域
struct student *next;//指针域
};
int n;
//建立链表函数,此函数返回一个指向链表头的指针
struct student *creat(void)//返回指针的函数,返回类型为student结构体类型。这里不写struct可以吗?TRY
{
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
printf("请输入学生编号和成绩(编号为0时将终止输入):\n");
scanf("%ld%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)//学生的编号num为0时表示终止输入
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);//这里的p1相当于一个临时指针,每次都重新申请空间
printf("请输入学生编号和成绩(编号为0时将终止输入):\n");
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;
return (head);
}
//打印链表内容函数
void print(struct student *head)
{
struct student *p;
p=head;
printf("\nnow,these %d records are:\n",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 *p1,*p2;
if(head==NULL)//如果头指针为空
{
printf("\nlist null!\n");goto end;
}
p1=head;
while(num!=p1->num)
{
if(p1->next==NULL) break;
p2=p1;//p2相当于临时指针,p2不随后面p1的变化而变化,因为p2的地址已经确定,除非while循环中再次对它的指向做修改
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)//如果p1是头指针
head=p1->next;//头指针指向p1的下一个指针域,即删除head指针
else p2->next=p1->next;//删除p1指针的值域
n--;
printf("delete:%ld,%ld\n",num,p1->num);
}
else printf("%ld not been found!\n",num);
end:
return (head);
}
//插入结点函数
struct student *insert(struct student *head,struct student *pn)
{
struct student *pc,*pa;
pc=pa=head;
if(head==0)//NULL指针是一个无类型指针,并且值为0。
{
head=pn;
pn->next=0;
return head;
}
if(pn->score>=head->score)
{
pn->next=head;
head=pn;
return head;
}
while(pc->next!=0&&pn->score<=pc->score)
{
pa=pc;
pc=pc->next;
}
if(pn->score<=pc->score)
{
pc->next=pn;
pn->next=0;
}
else
{
pn->next=pc;
pa->next=pn;
}
return head;
}
int main()
{
struct student *head,*stu;
long del_num;
printf("input records:\n");
head=creat();
print(head);
printf("\ninput the deleted number:");
scanf("%ld",&del_num);
while(del_num!=0)
{
head=del(head,del_num);
print(head);
printf("input the deleted number:");
scanf("%ld",&del_num);
}
printf("\ninput the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld,%f",&stu->num,&stu->score);
while(stu->num!=0)
{
head=insert(head,stu);
print(head);
printf("input the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld%f",&stu->num,&stu->score);
}
return 0;
}