#include
#include
#include#define LEN sizeof(struct Student)
#define N1 3 //链表结点个数
#define N2 2struct Student *Create(int n); //创建链表
void Print(struct Student *head); //输出链表
void Fang(struct Student **head); //释放链表
void P(struct Student *head); //链表排序
struct Student *Link(struct Student *head1,struct Student *head2); //合并有序链表struct Student
{char xh[12];float score;struct Student *next;
};#include
int main()
{struct Student *head1,*head2,*head;printf("请输入第一个链表的学生信息:\n");head1=Create(N1);printf("请输入第二个链表的学生信息:\n");head2=Create(N2);P(head1); //链表升序排序P(head2);head=Link(head1,head2); //升序连接连接链表printf("合并链表后排序为:\n");Print(head);Fang(&head);//Fang(&head1); //这里还是跟我另一个程序一样,整的我抓耳挠腮的,//忘记自己已经连接改变了他们的头指针,所以假如这里//是释放head1,2就会出错,而且我还一直看的是连接的函数,导致浪费了很多时间,已经都怀疑电脑的问题了return 0;
}struct Student *Create(int n)
{struct Student *head=NULL,*p,*p1; int i=0;while(ixh ,&p->score );p->next=NULL;if(head==NULL){head=p;p1=p;}else{p1->next =p;p1=p;}i++;}return head;
}void Print(struct Student *head)
{struct Student *p;p=head;while(p!=NULL){printf("%s,%.1f\n",p->xh ,p->score );p=p->next ;}
}void Fang(struct Student **head)
{struct Student *p;while(*head!=NULL){p=*head;*head=(*head)->next ;free(p);}*head=NULL;
}void P(struct Student *head) //这个就是对链表进行升序
{struct Student *p,temp; //这里的temp不用指针类型,因为我们只是把他当作一个中介来存取东西而已,他不跟别人交流p=head;int i=0;while(p!=NULL) //算算多少个结点,看看我们排序要走到哪里{i++;p=p->next;}int j,k;p=head;for(j=0;jnext比较,如果不减去1,第一次的最后一个p->next就是NULL {p=head; //不要忘记每次从头开始奥,别跟无头苍蝇一样四处乱窜哈for(k=0;kxh ,p->next ->xh )>0) //这里就是朴实无华的交易场所{strcpy(temp.xh ,p->xh);strcpy(p->xh ,p->next ->xh);strcpy(p->next ->xh ,temp.xh );temp.score =p->score ;p->score =p->next ->score ;p->next ->score =temp.score ;}p=p->next ;}}
}
struct Student *Link(struct Student *head1,struct Student *head2) //重头戏,升序连接
{struct Student *head=NULL,*p; //这里只需要一个头指针跟连接的指针if(head1==NULL&&head2==NULL) //判断是否有空,若是其中一个为空返回另一个return NULL;else if(head1==NULL)return head2;else if(head2==NULL)return head1;if(strcmp(head1->xh,head2->xh )<0) //到这里就说明都不为空,那么就先比较两个链表的第一个谁小就先把谁放进去新的链表,然后他后移一位{head=head1;p=head; head1=head1->next ;}else {head=head2;p=head;head2=head2->next ;}while(head1!=NULL&&head2!=NULL) //两个都没有到尾部时继续刚刚的操作比较{if(strcmp(head1->xh,head2->xh )<0){if(strcmp(p->xh,head1->xh )==0 )head1=head1->next ;else{p->next =head1;p=head1;head1=head1->next ;}}else{if(strcmp(p->xh,head2->xh )==0 )head2=head2->next ;else{p->next =head2;p=head2;head2=head2->next ;}}}if(head1==NULL) //表示一个已经到为节点,比较这个链表是否有相同的结点,相同的跳过{while(head2!=NULL){if(strcmp(p->xh,head2->xh )==0 )head2=head2->next ;else{p->next =head2;p=head2;head2=head2->next ;}}}else if(head2==NULL){while(head1!=NULL){if(strcmp(p->xh,head1->xh )==0 )head1=head1->next ;else{p->next =head1;p=head1;head1=head1->next ;}}}elsep->next =NULL;return head;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!