求助归并算法问题

李万鹏 2009-10-23 10:33:42
请大虾帮忙找一下问题 十分感谢
struct student * guibing(struct student *head1,struct student *head2){
struct student * newhead = NULL,*p3 = NULL;
struct student *p1 = head1,*p2 = head2;
newhead = p3 = head1;
while(p1 != NULL && p2 != NULL){
if(newhead == NULL){
if(p1->number < p2->number){
newhead = p3 = p1;
p1 = p1->next;
}
else{
newhead = p3 = p2;
p2 = p2->next;
}
}
else{
if(p1->number < p2->number){
p3->next = p1;
p3 = p1;
p1 = p1->next;
}
else{
p3->next = p2;
p3= p2;
p2 = p2->next;
}
}
}
p3->next = p1?p1:p2;
return newhead;
}
...全文
106 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
asimay 2009-10-23
  • 打赏
  • 举报
回复
感觉p3没有分配内存呢。。。

归并嘛,肯定是新分配的内存单元。
whg01 2009-10-23
  • 打赏
  • 举报
回复
明天再看。
李万鹏 2009-10-23
  • 打赏
  • 举报
回复
1,34
3,56
5,78
0
2,56
4,67
是这样输入的呀
whg01 2009-10-23
  • 打赏
  • 举报
回复
你是怎么输入的?
输入head1时,必须是排好序的。head2也是如此。
归并排序只是对已排好序的2个队列进行合并。如果2个队列内部没有排序,那么归并的结果肯定不对。
李万鹏 2009-10-23
  • 打赏
  • 举报
回复
这是我完整的程序 除了归并函数 其他都对
#include <stdio.h>
#include <stdlib.h>
struct student{
int number;
int score;
struct student * next;
};
struct student * creat(){
struct student *head = NULL,*p=NULL,*q=NULL;
p = (struct student *)malloc(sizeof(struct student));
scanf("%d,%d",&p->number,&p->score);
while(p->number != 0){
if(head == NULL)
head = q = p;
else{
q->next = p;
q = p;
}
p = (struct student *)malloc(sizeof(struct student));
scanf("%d,%d",&p->number,&p->score);
}
q->next = NULL;
return head;
}
struct student * guibing(struct student *head1,struct student *head2){
struct student * newhead = NULL,*p3 = NULL;
struct student *p1 = head1,*p2 = head2;
newhead = p3 = head1;
while(p1 != NULL && p2 != NULL){
if(newhead == NULL){
if(p1->number < p2->number){
// newhead = p3 = p1;
p1 = p1->next;
}
else{
newhead = p3 = p2;
p2 = p2->next;
}
}
else{
if(p1->number < p2->number){
p3->next = p1;
p3 = p1;
p1 = p1->next;
}
else{
p3->next = p2;
p3= p2;
p2 = p2->next;
}
}
}
p3->next = p1?p1:p2;
return newhead;
}
void print(struct student *head){
struct student *p = head;
if(head == NULL)
printf("表为空");
else
while(p != NULL){
printf("%d,%d\n",p->number,p->score);
p = p->next;
}
}
int main(){
struct student *head1,* head2,* newhead;
head1 = creat();
head2 = creat();
newhead = guibing(head1,head2);
print(newhead);
system("pause");
return 0;
}
李万鹏 2009-10-23
  • 打赏
  • 举报
回复
还是没有正确结果呀
whg01 2009-10-23
  • 打赏
  • 举报
回复
newhead = p3 = head1; //while循环上的这句删掉就好了。
因为没有比较head1和head2的大小关系,所以不能设置newhead和p3。
while循环里会处理。
李万鹏 2009-10-23
  • 打赏
  • 举报
回复
我是问错在哪

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧