求助:为什么得不到正确结果?(在线等)
数据结构问题:用单链表实现A+B的并集,A和B都是按升序排列。
我的代码如下,望高手帮忙看看!(用c实现)
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct linknode
{
int data;
struct linknode *next;
}node;
node *create() //建立链表
{
node *head, *p, *s;
int x, cycle = 1;
head = new node;
p = head;
while(cycle)
{
s = new node;
cin >> x;
if(x != 0)
{
s->data = x;
p->next = s;
p = s;
}
else cycle = 0;
}
p->next = NULL;
s = head;
head = head->next;
delete s;
return head;
};
void print(node *head) //打印链表
{
node *p;
p = head;
while(p != NULL)
{
cout << p->data;
p = p->next;
}
cout << endl;
};
node *unionA_B(node * ha, node *hb)//求并集
{
node *p, *q,*hc,*r,*s;
hc = new node;
r = hc; p = ha; q = hb;
while(p != NULL && q != NULL)
{
if(p->data < q->data)
{
s = new node;
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
else if(p->data > q->data)
{
s = new node;
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
else
{
s = new node;
s->data = p->data;
r->next = s;
r = s;
q = q->next;
p = p->next;
}
}
if(p = NULL)
while(q != NULL)
{
s = new node;
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
if(q = NULL)
while( p != NULL)
{
s = new node;
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
r->next = NULL;
s = hc;
hc = hc->next;
delete s;
return hc;
};
int main()
{
node *h1, *h2, *h3;
h1 = create();
print(h1);
h2 = create();
print(h2);
h3 = unionA_B(h1, h2);
print(h3);
return 0;
}