在LinkedList中组合具有相同功率值的相同元素

时间:2014-01-25 18:53:33

标签: java

我有这个PolyNode类:

public class PolyNode
{
    private int _power;
    private double _coefficient;
    private PolyNode _next;

        public PolyNode (int power, double coefficient)...
        public PolyNode(int power, double coefficient,PolyNode next)...
        public PolyNode(PolyNode p)...
        public int getPower()...
        public double getCoefficient()...
        public  PolyNode getNext()...
        public void setPower(int power)...
        public void setCoefficient (double coefficient)...
        public void setNext(PolyNode next)...
}

这个Polynom课程:

public class Polynom
{
   private PolyNode _head;

   methods...  

}

我的一个方法是public Polynom multPol (Polynom other)多个这个Polynom和另一个Polynom例如:

pol1 = ...
pol2 = ...
so pol1 * pol2 = 9x^5 + 18x^3 -6x^3 -18x^2
and i want to combine same power value so 18x^3 -6x^3 become 12x^3

这是我的多功能函数:

    public Polynom multPol (Polynom other)
    {   

        if (other != null)
        {
            // Define new Polynom
            Polynom pol = new Polynom();

            for (PolyNode tmp = _head; tmp != null; tmp = tmp.getNext())
            {
                for (PolyNode otherList = other._head; otherList != null; otherList = otherList.getNext())
                {
                    double coefficient = tmp.getCoefficient() * otherList.getCoefficient();
                    int power = tmp.getPower() + otherList.getPower();
                    PolyNode node = new PolyNode(power, coefficient);
                    pol.addNode(node);
                }
            }

            // Make our new Polynom this (move pointer)
            _head = pol._head;
        }

        return this;
    }

这就是我试图缩小我的名单:

    private void shrinkList()
    {
        int listLength = GetListLength(this);
        Polynom pol = new Polynom();
        PolyNode cur = _head;
        int count = 0;

        while (count < listLength)
        {
            for (PolyNode tmp = _head.getNext(); tmp != null; tmp = tmp.getNext())
            {           
                if (cur.getPower() == tmp.getPower())
                {
                    double coefficient = tmp.getCoefficient();
                    int power = tmp.getPower();
                    PolyNode node = new PolyNode(power, coefficient);
                    pol.addNode(node);
                }
            }

            cur = cur.getNext();
            count++;
        }
    }

0 个答案:

没有答案