Java中的多项式表示

  • 本文关键字:表示 多项式 Java java
  • 更新时间 :
  • 英文 :


我想用链表来表示一个多项式。下面是我的代码

import java.io.*;
import java.util.*;
public class Multiply_Poly
{
    polynode head;
    Multiply_Poly()
    {
        head=null;
    }
    public void construct_poly(polynode head,float coeff,int exp)
    {
        if(head==null)
        {
            polynode newnode = new polynode(coeff,exp);
            head=newnode;
            return;
        }
        else
        {
            polynode newnode = new polynode(coeff,exp);
            polynode temp = head;
            while(temp.next!=null)
                temp=temp.next;
            temp.next=newnode;
            temp=newnode;
        }
    }
    public void show_poly(polynode head)
    {
        if(head==null)
            return;
        else
        {
            while(head.next!=null)
            {
                System.out.print("(" + head.coeff + ")" + "x^" + "(" + head.exp + ")" + "+");
                head=head.next;
            }
            System.out.print("(" + head.coeff + ")" + "x^" + "(" + head.exp + ")");
        }
    }
    public static void main(String [] args)
    {
        Multiply_Poly m = new Multiply_Poly();
        m.construct_poly(m.head,12,5);
        m.construct_poly(m.head,9,4);
        m.construct_poly(m.head,26,3);
        m.construct_poly(m.head,18,2);
        m.construct_poly(m.head,10,1);
        m.construct_poly(m.head,5,0);
        m.show_poly(m.head);
    }
}
class polynode
{
    float coeff;
    int exp;
    polynode next;
    polynode(float coeff,int exp)
    {
        this.coeff=coeff;
        this.exp=exp;
        next=null;
    }
}

我认为我的construct_poly函数不工作。这就是为什么show_poly函数返回null。我的其他部分在construct_poly是不是写正确?我错在哪里?

if(head==null)部分的construct_poly方法中只需更改

head=newnode; 
to this.head=newnode;

这样做的原因是,你想参考你的类变量多节点头,即在链表的开始,但只使用头(不是this.head)编译器将其引用为参数传递的局部变量头。

所以我们使用this。head指向调用对象的类变量。

记住:局部变量的优先级总是高于全局变量。

也不需要最后一行else部分,即

temp=newnode;
不需要

最新更新