两个 链表的合并不知道为啥 程序运行怎么就不对呢#include<stdio.h>
#include <string.h>
#include <stdlib.h>
struct jg
{
int data;
struct jg *next;
};
void attach(int a, struct jg** nrear)
{
struct jg *p;
p = (struct jg *)malloc(sizeof(struct jg));
p->data = a;
p->next = NULL;
(*nrear)->next = p;
*nrear = p;
}
struct jg* read()
{
struct jg* p;
struct jg* rear;
struct jg* t;
p=(struct jg *)malloc(sizeof(struct jg));
int a, m;
scanf("%d", &a);
p->next=NULL;
rear=p;
while (a--)
{
scanf("%d", &m);
attach(m,&rear);
}
t = p;
p = p->next;
free(t);
return p;
}
struct jg* add( struct jg* p1,struct jg* p2)
{
struct jg *p, *rear, *t;
p = (struct jg *)malloc(sizeof(struct jg));
rear = p;
p->next = NULL;
while(p1&&p2)
{
if (p1->data > p2->data)
{
attach(p2->data, &rear);
p2 = p2->next;
}
else if (p1->data = p2->data)
{
attach(p1->data, &rear);
p1 = p1->next;
p2=p2->next;
}
else
{
attach(p1->data, &rear);
p1 = p1->next;
}
}
while (p1)
{
attach(p1->data, &rear);
p1 = p1->next;
}
while(p2)
{
attach(p2->data, &rear);
p2 = p2->next;
}
t = p;
p = p->next;
free(t);
return p;
}
void print( struct jg *p1)
{
int a = 0;
while(p1)
{
if (a ==0)
{
a = 1;
}
else
{
printf(" ");
}
printf("%d",p1->data);
p1= p1->next;
}
}
int main()
{
struct jg *p1, *p2,*p3;
p1 = read();
p2 = read();
p3 = add(p1, p2);
print(p3);
system("pause");
return 0;
}
1 回答
qq_追梦_26
TA贡献15条经验 获得超2个赞
1:" else if (p1->data = p2->data)"粗心了吧(==)?
2:别free,应为你后面的printf要用到这块内存 p = (struct jg *)malloc(sizeof(struct jg)),你程序不是很长也许你感觉不到free以后那一块地方会被改
3:按理来说你得先给每个链表排序,然后再连接,否则像你这个案例输出只能是“1 5 4 6”而不是“1 4 5 6”
- 1 回答
- 0 关注
- 1481 浏览
添加回答
举报
0/150
提交
取消