Soumya Kanti Naskar
Soumya Kanti Naskar

Reputation: 1081

Polynomial Representation in Java

I want to represent a polynomial with the help of linked list. Here goes my code

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;
    }
}

I think my construct_poly function is not working. That's why show_poly function returns null. Is my else part in construct_poly is not written correctly ? What is my mistake ?

Upvotes: 0

Views: 533

Answers (1)

Rahul Agrawal
Rahul Agrawal

Reputation: 633

In the construct_poly method in if(head==null) part just change

head=newnode; 
to this.head=newnode;

Reason for doing is that you want to refer to your class variable polynode head i.e. at the beginning of your linked list, but using only head(not this.head) compiler refers it to local variable head passed as argument.

So we use this.head to refer to class variable of calling object.

REMEMBER: Local variables always have higher priority than global variables.

Also there is no need of last line of else part i.e.

temp=newnode;

is not required.

After above changes your code runs perfectly fine.

Upvotes: 1

Related Questions