我的输出特别奇怪,麻烦大家帮我看看
题目:已知链表 LA 按值非递增有序排列,LB 按值非递减有序排列,现要求将 LA和 LB 归并为一个新的链表 LC,且 LC 中的数据元素按值非递减有序排列
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int date;
struct node* next;
}node,*list;
list create();
void nizhi(list A);
void combine(list A,list B);
int main()
{
list A=create();
list B=create();
void nizhi(A);
combine(A,B);
return 0;
}
list create()
{
int x;
scanf("%d",&x);
list head=(list)malloc(sizeof(node));
head->next=NULL;
head->date=0;
list q=head;
do{
list p=(list)malloc(sizeof(node));
p->date=x;
q->next=p;
p->next=NULL;
q=p;
}while(getchar()!='\n');
return head;
}
void nizhi(list A)
{
list p=A->next;
A->next=NULL;
while(p){
list r=p->next;
p->next=A->next;
A->next=p;
p=r;
}
}
void combine(list A,list B)
{
list C=(list)malloc(sizeof(node));
C->date=0;
C->next=NULL;
list t=C;
list p=A->next;
list q=B->next;
while(p&&q){
list s=(list)malloc(sizeof(node));
if(p->date<q->date){
s->date=p->date;
t->next=s;
t=s;
p=p->next;
}
else if(p->date>q->date){
s->date=q->date;
t->next=s;
t=s;
q=q->next;
}
}
if(p){
t->next=p;
}
else if(q){
t->next=q;
}
list f=C->next;
while(f){
printf("%d ",f->date);
f=f->next;
}
}
修改处见注释,供参考。另:将 LA和 LB 归并为一个新的链表 LC,是否需要申请新的空间,值得商榷,代码里是生成一部分,后面又截取部分原来的。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int date;
struct node* next;
}node, * list;
list create();
void nizhi(list A);
void combine(list A, list B);
int main()
{
list A = create();
list B = create();
nizhi(A); //void nizhi(A); 函数调用 修改
combine(A, B);
return 0;
}
list create()
{
int x;
//scanf("%d", &x); 修改
list head = (list)malloc(sizeof(node));
head->next = NULL;
head->date = 0;
list q = head;
do {
scanf("%d", &x); //输入 x 应放在 do{}while;循环体里 修改
list p = (list)malloc(sizeof(node));
p->date = x;
q->next = p;
p->next = NULL;
q = p;
} while ((getchar()) != '\n');
return head;
}
void nizhi(list A)
{
list p = A->next;
A->next = NULL;
while (p) {
list r = p->next;
p->next = A->next;
A->next = p;
p = r;
}
}
void combine(list A, list B)
{
list C = (list)malloc(sizeof(node));
C->date = 0;
C->next = NULL;
list t = C;
list p = A->next;
list q = B->next;
while (p && q) {
list s = (list)malloc(sizeof(node));
s->next = NULL; //修改
if (p->date < q->date) {
s->date = p->date;
t->next = s;
t = s;
p = p->next;
}
else { //if (p->date > q->date) { 修改
s->date = q->date;
t->next = s;
t = s;
q = q->next;
}
}
if (p) {
t->next = p;
}
if (q) { //else if (q) 修改
t->next = q;
}
list f = C->next;
while (f) {
printf("%d ", f->date);
f = f->next;
}
}