Java语言使用单项链表来计算多项式的求和的功能,链表的实现可以使用上个星期的作业中定义的
2条回答 默认 最新
- 这不是鸭头 2020-04-09 15:24关注
//定义节点类
class Node{
public int coef;//系数
public int exp;//指数
public Node next=null;//下个节点
public Node(){
coef=0;
exp=0;
}
public Node(int coef,int exp){
this.coef=coef;
this.exp=exp;
}
}
//多项式类
public class PolynList {
//多项式相加
public Node add(Node link1, Node link2) {
Node pre=link1;
Node qre=link2;
Node p=pre.next;
Node q=qre.next;
Node result=p;
while(p!=null && q!=null){
if(p.exp pre=p;
p=p.next;
}else if(p.exp>q.exp){
Node temp=q.next;
pre.next=q;
q.next=p;
q=temp;
}else{
p.coef=p.coef+q.coef;
if(p.coef==0){
pre.next=p.next;
p=pre.next;
}else{
pre=p;
p=p.next;
}
qre.next=q.next;
q=qre.next;
}
}
if(q!=null){
pre.next=q;
}
return result;
}//添加数据方法 public Node insert(Node link,int coef,int exp) {//添加节点 Node node=new Node(coef,exp); if(link==null){ link.next=node; }else{ Node temp=link; while(temp.next!=null){ temp=temp.next; } temp.next=node; } return link; } }
//主方法
public static void main(String[] args) {
PolynList ts = new PolynList();
Node link1=new Node();
Node link2=new Node();
//第一个多项式
ts.insert(link1,4,0);
ts.insert(link1,5,2);
ts.insert(link1,4,8);
ts.insert(link1,6,12);
//第二个多项式
ts.insert(link2,6,1);
ts.insert(link2,6,3);
ts.insert(link2,3,8);
ts.insert(link2,4,15);
ts.insert(link2,8,20);link1 = ts.add(link1, link2); while(link1!=null){ if(link1.exp== 0) System.out.print(link1.coef); else System.out.print(link1.coef+"x^"+link1.exp); link1=link1.next; if(link1!=null) System.out.print("+"); } }
}
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
- ¥15 Windows11, backspace, enter, space键失灵