多项式的相加

jieao111 2008-04-03 02:35:29

我输入是安照。。高次到低次的,,,又有什么逻辑错误,,我看了好几遍

#include "stdafx.h"
#include<iostream>
using namespace std;
struct Node
{
int a,b;
Node* next;
};
void intit(Node* &head)
{
int nit,pit;
head=new Node;
Node* m=head;
cout<<"PLEASE";
for(int i=0;i<1;++i)
{
cin>>nit>>pit;
Node* p=new Node;
p->a=nit;
p->b=pit;
m->next=p;
p->next=NULL;
m=m->next;

}
}
void print(Node* head)
{
Node* p=head;
p=p->next;
while(p)
{

cout<<p->a<<"X^"<<p->b<<endl;
p=p->next;

}
}
void merge(Node* &head1,Node* &head2,Node* &head)
{
Node* p=head1;
Node* q=head2;
Node* m=head;
head=new Node;
p=p->next;
q=q->next;
//p=p->next;
while(p&&q)
{
if(p->b>q->b)
{
m->next=p;
//p->next=NULL;//这里该不该有这句呢,,我想它插入m中,应该为NULL。。而它后面又那句p=p->next;,,该怎么处理呢?
p=p->next;
m=m->next;
}
else if(p->b<q->b)
{
m->next=q;
//q->next=NULL;
q=q->next;
m=m->next;
}
else if((p->b)==(q->b))
{
(p->a)+=(q->a);
m->next=p;
//p->next=NULL;
p=p->next;
q=q->next;
m=m->next;
}

}
}
int main()
{
Node *head1,*head2,*head;
intit(head1);
intit(head2);
print(head1);
print(head2);
merge(head1,head2,head);
print(head);
return 0;
}
...全文
162 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wujun6042 2008-06-10
  • 打赏
  • 举报
回复
在哪里?
ryfdizuo 2008-04-04
  • 打赏
  • 举报
回复
建议你去看一下别人写好的代码,
hastings 2008-04-03
  • 打赏
  • 举报
回复
2楼小改一下:
if(p)
{
m->next=p;
}
if(q)
{
m->next=q;
}
hastings 2008-04-03
  • 打赏
  • 举报
回复
struct Node
{
int a,b;
Node* next;
};
void intit(Node* &head)
{
int nit,pit;
head=new Node;
Node* m=head;
m->next=0;
cout<<"Please input :\n";
while(cin>>nit>>pit && !(nit==0&&pit==0))
{
Node* p=new Node;
p->a=nit;
p->b=pit;
m->next=p;
p->next=NULL;
m=m->next;
}
}
void clear(Node* &head)
{
Node* p=head;
while(p)
{
head=head->next;
delete p;
p=head;
}
}
void print(const Node* head)
{
const Node* p=head;
p=p->next;
if(p)
{
cout<<p->a<<"X^"<<p->b<<' ';
p=p->next;
}
while(p)
{
if(p->a>0)
cout<<'+';
cout<<p->a<<"X^"<<p->b<<' ';
p=p->next;
}
cout<<'\n';
}
void merge(Node* &head1,Node* &head2,Node* &head)
{
Node* p=head1;
Node* q=head2;
head=new Node;
Node* m=head;
m->next=0;
p=p->next;
q=q->next;
while(p&&q)
{
if(p->b>q->b)
{
m->next=p;
p=p->next;
m=m->next;
}
else if(p->b<q->b)
{
m->next=q;
q=q->next;
m=m->next;
}
else if((p->b)==(q->b))
{
(p->a)+=(q->a);
m->next=p;
p=p->next;
{
Node* tmp=q;
q=q->next;
delete tmp;
}
m=m->next;
}
}
while(p)
{
m->next=p;
}
if(q)
{
m->next=q;
}
delete head1;
delete head2;
head1=0;
head2=0;
}
int main()
{
Node *head1,*head2,*head;
intit(head1);
intit(head2);
print(head1);
print(head2);
merge(head1,head2,head);
print(head);
clear(head);
return 0;
}
迦叶123 2008-04-03
  • 打赏
  • 举报
回复
在intit中head已经随着函数的返回而撤销了!

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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