2016-08-16 56 views
0

我想借助链表来表示一个多项式。这里去我的代码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中的其他部分是不是正确写入?我的错误是什么?

+1

你和'head'有一个命名冲突。从所有方法中删除'head'参数。 – molbdnilo

+0

同样的事情发生时,我用任何其他参数替换头@molbdnilo –

+0

@SoumyaKantiNaskar想一想,当你给函数的参数赋值时会发生什么。删除'polynode'参数。你应该有'public void construct_poly(float coeff,int exp)'。你应该看看你最喜欢的Java书中关于类和对象的章节。 – molbdnilo

回答

1

的construct_poly方法,如果(头== NULL)部分只是改变

head=newnode; 
to this.head=newnode; 

理由这样做是要指即在你的链接开始你的类变量polynode头列表,但只使用head(not this.head)编译器将其引用为作为参数传递的局部变量头。

所以我们使用this.head来引用调用对象的类变量。

注意:局部变量的优先级总是高于全局变量。

也没有必要else部分即

temp=newnode; 

的最后一行是不需要的。

上述更改后,您的代码运行得很好。