#include
#include<malloc.h>
using namespace std;
typedef struct LN
{
int data;
struct LN* next;
}LN, * LinkList;
void CreateList_L(LinkList& L, int n)
{
LinkList p, q = L;
L = (LinkList)malloc(sizeof(LN));
L->next = NULL;
while (n--)
{
p = (LinkList)malloc(sizeof(LN));
cin >> p->data;
q->next = p;
p->next = NULL;
q = p;
}
}
void MergeList(LinkList& L1, LinkList L2)
{
LinkList p, q, r;
r = L1;
p = L1->next;
q = L2->next;
while (p && q)
{
if (q->data <= p->data)
{
r->next = q;
r = r->next;
q = q->next;
}
else
{
r->next = p;
r = r->next;
p = p->next;
}
}
if (p)r->next = p;
if (q)r->next = q;
}
void output(LinkList L)
{
LinkList p;
p = L->next;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
}
int main()
{
int x1, x2;
LinkList L1, L2;
cin >> x1 >> x2;
CreateList_L(L1, x1);
CreateList_L(L2, x2);
MergeList(L1, L2);
output(L1);
}
q = L; // q要在L分配了空间后,再指向l
你题目的解答代码如下:
#include<iostream>
#include <malloc.h>
using namespace std;
typedef struct LN
{
int data;
struct LN *next;
} LN, *LinkList;
void CreateList_L(LinkList &L, int n)
{
LinkList p, q;
L = (LinkList)malloc(sizeof(LN));
q = L; // q要在L分配了空间后,再指向l
L->next = NULL;
while (n--)
{
p = (LinkList)malloc(sizeof(LN));
cin >> p->data;
q->next = p;
p->next = NULL;
q = p;
}
}
void MergeList(LinkList &L1, LinkList L2)
{
LinkList p, q, r;
r = L1;
p = L1->next;
q = L2->next;
while (p && q)
{
if (q->data <= p->data)
{
r->next = q;
r = r->next;
q = q->next;
}
else
{
r->next = p;
r = r->next;
p = p->next;
}
}
if (p)
r->next = p;
if (q)
r->next = q;
}
void output(LinkList L)
{
LinkList p;
p = L->next;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
}
int main()
{
int x1, x2;
LinkList L1, L2;
cin >> x1 >> x2;
CreateList_L(L1, x1);
CreateList_L(L2, x2);
MergeList(L1, L2);
output(L1);
}
如有帮助,望采纳!谢谢!
void CreateList_L(LinkList& L, int n)函数中,q = L;需要放在L = (LinkList)malloc(sizeof(LN));这一句的下面。否则q和L都是未初始化的变量。
修改如下:
void CreateList_L(LinkList& L, int n)
{
LinkList p, q ;//修改1 q= L;
L = (LinkList)malloc(sizeof(LN));
L->next = NULL;
q = L;//修改2 在这里用q记录L的值
while (n--)
{
p = (LinkList)malloc(sizeof(LN));
cin >> p->data;
q->next = p;
p->next = NULL;
q = p;
}
}