|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
#define N 3
struct student
{
int num;
float score;
struct student *next;
};
struct student *creat();
struct student *del(struct student *head,int num);
struct student *insert(struct student *head,struct student *stu_2);
void print(struct student *head);
int n;
void main()
{
struct student *stu;
struct student std[N]={{},{},{}};
int n,i;
stu=creat();
print(stu);
printf("\n\n");
printf("please enter the num to delete:");
scanf("%d",&n);
print(del(stu,n));
for(i=0;i<N;i++)
{
printf("\nplease input the num to insert:");
scanf("%d",&stu[i].num);
printf("please input the score:");
scanf("%f",&stu[i].score);
stu=insert(stu,&stu[i]);
print(stu);
}
printf("\n\n");
}
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
p1=p2=(struct student *)malloc(LEN);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num)
{
n++;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("\nplease enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
};
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("\nThis list is null!\n");
goto END;
}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{
p2=p1;
p1=p2->next;
}
if(p1->num==num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
printf("\nDelete No: %d succeed!\n",num);
n=n-1;
}
else
{
printf("%d not been found!\n",num);
}
END:
return head;
};
struct student *insert(struct student *head,struct student *stu_2)
{
struct student *p0,*p1,*p2;
p1=head;
p0=stu_2;
if(NULL==head)
{
head=p0;
p0->next=NULL;
}
else
{
while((p0->num>p1->num)&&(p1->next!=0))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(p1==head)
{
head=p0;
}
else
{
p2->next=p0;
}
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;
return head;
};
void print(struct student *head)
{
struct student *p;
printf("\nThere are %d records!\n\n",n);
p=head;
if(head)
{
do
{
printf("学号为%d的成绩是:%f\n",p->num,p->score);
p=p->next;
}while(p);
}
}
你的意思是想像字符串扩展一样,可以将两个不同长度的链表合成一个?
其实这个是可行并且无意义的,
架设有一个链表头指针 head1,以及需要插入的另一个链表头指针head2,以及临时指针temp,使用头插法。
temp = head1; //将head1储存到临时指针
head1 = head2; //将head1赋值为head2
/* 这里就相当于把head2这个列表接入head1的头*/
/* 将head2列表眺到最后一个结构,我这里省略*/
head2->next = temp; //将原列表后面的结构连上来
其实对于链表来说,不管是一次添加一个还是一次添加多个,都是同样的操作方法。而这种方法的前提是这两个链表应使用同一种结构。
|
|