求助:为什么得不到正确结果?(在线等)

Darren1982 2004-11-05 12:00:43
数据结构问题:用单链表实现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;
}
...全文
110 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Darren1982 2004-11-05
  • 打赏
  • 举报
回复
按照题目要求,要用单链表!
不用c++
avalonBBS 2004-11-05
  • 打赏
  • 举报
回复
using namespace std;
c里面是没有这个的:)


试试这个
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
using namespace std;
template <class T>
void U(vector<T>& d,const vector<T>& s1,const vector<T>& s2)
{//并集
typename vector<T>::const_iterator iter;
for(iter=s2.begin();iter!=s2.end();iter++)
d.push_back(*iter);
for(iter=s1.begin();iter!=s1.end();iter++){
if(find(s2.begin(),s2.end(),*iter) ==s2.end())
d.push_back(*iter);
}
}
int main(void)
{
int a[]={1,23,1234,12,45,34,5421};
int b[]={123,34,54,12,454,45};
vector<int> s1(a,a+7),s2(b,b+6);
vector<int> d;
U(d,s1,s2);
//输出
vector<int>::iterator iter;
for(iter=d.begin();iter!=d.end();iter++)
cout<<*iter<<endl;
system("pause");
return 0;
}
yanglight 2004-11-05
  • 打赏
  • 举报
回复
你考虑错了,我要是输入的不是按从小到大或者从打到小的顺序,会有重复的情况
Darren1982 2004-11-05
  • 打赏
  • 举报
回复
唉,真是惭愧,犯了个低级错误,
楼上的我的代码里面有考虑相同元素的合并,
你可能没看到!
yanglight 2004-11-05
  • 打赏
  • 举报
回复
注意你的球并及运算没有考虑相同元素的合并,自己完成!!!
yanglight 2004-11-05
  • 打赏
  • 举报
回复
//在你的求并集函数中的者几句有错
if(p = NULL)
/////////////改为if(p==NULL)
while(q != NULL)
{
s = new node;
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
if(q = NULL)
/////////////改为if(p==NULL)
while( p != NULL)
{
s = new node;
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}

69,337

社区成员

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

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