动态链表的插入
根据学生的学号顺序进行插入
1)如果原本的链表为空
2)如果原本的链表是单元素链表----->在头部,在尾部
3)如果原本的链表是多元素链表----->在头部,在中间,在尾部
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student{
int ID;
char Name[10];
struct Student*Next;
};
int Student_Num;
struct Student*Creat(void){
struct Student*p1,*p2,*head;
head=NULL;
p1=(struct Student*)malloc(LEN);
scanf("%d %s",&p1->ID,p1->Name);
while(p1->ID>0){
Student_Num++;
if(Student_Num==1){
head=p1;
}
else{
p2->Next=p1;
}
p2=p1;
p1=(struct Student*)malloc(LEN);
scanf("%d %s",&p1->ID,p1->Name);
}
if(head!=NULL) p2->Next=NULL;
return (head);
}
struct Student*Insert(struct Student*head,struct Student stu){
struct Student*p1,*p2;
int Num_Temp;
p2=p1=head;
Num_Temp=Student_Num;
if(p1!=NULL){
do{
//单元素链表
if(Num_Temp==1){
//插在尾部
if(p1->ID<stu.ID){
p1->Next=&stu;
stu.Next=NULL;
Student_Num++;
}
//插在头部
else{
head=&stu;
stu.Next=p1;
Student_Num++;
}
}
//多元素链表
else{
//插在头部
if(p1->ID>stu.ID){
head=&stu;
stu.Next=p1;
Student_Num++;
}
//插在中间或者尾部
else{
//插在尾部
if(p1->Next==NULL){
p1->Next=&stu;
stu.Next=NULL;
Student_Num++;
}
//插在中间
else{
//因为一开始赋值p1=p2,如果出现要插在第二个上就会有bug
if(p1==p2){
p1=p1->Next;
}
p2->Next=&stu;
stu.Next=p1;
Student_Num++;
}
}
}
}while(Student_Num==Num_Temp);
}
else{
head=&stu;
stu.Next=NULL;
}
return (head);
}
void Print(struct Student*head){
struct Student*Temp;
Temp=head;
if(Temp!=NULL){
do{
printf("%d %s\n",Temp->ID,Temp->Name);
Temp=Temp->Next;
}while(Temp!=NULL);
}
else printf("空链表!\n");
}
int main(){
struct Student*head,stu;
printf("如果学生的序号输入小于等于0的数,停止链表长度增加!\n");
head=Creat();
printf("\n原链表如下:\n");
Print(head);
printf("\n请输入你要插入的学生的信息:");
scanf("%d %s",&stu.ID,stu.Name);
while(stu.ID<=0){
printf("\n故意找茬是不是,学号还敢输错?\n");
printf("\n请输入你要插入的学生的信息:");
scanf("%d %s",&stu.ID,stu.Name);
}
head=Insert(head,stu);
printf("\n新链表如下:\n");
Print(head);
return 0;
}