链表排序问题
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student{
int num;
float score;
struct student * next;
};
int n;
int main(){
struct student * creat();
void print(struct student * head);
struct student * del(struct student * head, int num);
struct student * head1, * head2;
struct student * p1, * p2;
struct student * min;
int num, i;
struct student * newhead, *newpoint;
head1 = creat();
printf("print A list:\n");
print(head1);
head2 = creat();
printf("print B list:\n");
print(head2);
p1 = p2 = head1;
while(p1 != NULL){
p2 = p1;
p1 = p1->next;
}
p2->next = head2;
printf("add list.... :\n");
print(head1);
//////////////////////////////////////////
newhead = NULL;
for(i=0; i<n; i++){
p1 = p2 = min = head1;
num = p1->num;
while(p1!=NULL){
if(p1->num < num){
num = p1->num;
min = p1;
}
p2 = p1;
p1 = p1->next;
}
if(newhead == NULL){
newhead = min;
newpoint = newhead;
}
else{
newpoint->next = min;
newpoint = newpoint->next;
}
head1 = del(head1,min->num);
}
///////////////////////////////////////////////
newpoint->next = NULL;
printf("after 排序后:\n");
print(newhead);
return 0;
}
struct student * creat(){
struct student * head, * p1, * p2;
n = 0;
p1 = p2 = (struct student *)malloc(LEN);
printf("input num/score: \n");
scanf("%d %f", &p1->num, &p1->score);
head = NULL;
while(p1->num!=0){
n = n+1;
if(n == 1) head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(LEN);
printf("input num/score: \n");
scanf("%d %f", &p1->num, &p1->score);
}
p2->next = NULL;
return (head);
}
void print(struct student * head){
struct student * p;
p = head;
if(head != NULL)
do{
printf("%d %0.2f\n", p->num, p->score);
p = p->next;
}while(p!=NULL);
}
struct student * del(struct student * head, int num){
struct student * p1, * p2;
if(head == NULL){
printf("\nlist null!\n");
goto end;
}
p1 = head;
while(p1->num != num && p1->next != NULL){
p2 = p1;
p1 = p1->next;
}
if(num == p1->num){
if(p1 == head)
head = p1->next;
else
p2->next = p1->next;
}
else printf("not found!\n");
end: return(head);
}
做题的思路是,先创建2个新的链表,然后再合并成一个新的链表。随后针对这个合并的链表按序号进行排序。最后输出。我的思路是:利用快速排序的方法找出最小的,然后新建一个头结点和指针,指向最小的结点。然后通过删除结点的方法把最小的从链表中删除。然后再循环,直到退出。。。其他函数没有问题就是///////////的地方是我自己写的,我觉得有点问题。。现在运行结果只能输出第一个小的结点。有时候能输出2个结点。不知道为什么不能全部输出????还是我的思路有问题。
[解决办法]
啥意思...?
[解决办法]
利用快速排序的方法找出最小的,然后新建一个头结点和指针,指向最小的结点
找到最小的节点为何还要用快速排序的方法?比较一遍就好了,循环来做。
合并2个链表就是把一个尾节点指向另一个链表的头节点即可。然后一次快排即可。