用循环链表简化同幂多项式参数的系数

Simplify Coefficient of Same Power Polynomial Parameters With Circular LinkedList

此方法按顺序设置多项式的系数和指数值。
它工作正常。 ( val = coeff 和 val2 = exp )

public void setCoef(int val, int val2){

    Node nptr = new Node(val, val2, null, null);
    Node tmp, ptr;
    boolean ins = false;

    if (start == null)
    {
        nptr.setLinkNext(nptr);
        nptr.setLinkPrev(nptr);

        start = nptr;
        end = start;
    }
    else if (val2 >= start.getData2())
    {
        nptr.setLinkPrev(end);
        end.setLinkNext(nptr);

        start.setLinkPrev(nptr);
        nptr.setLinkNext(start);

        start = nptr;
    }
    else if (val2 <= end.getData2())
    {
        end.setLinkNext(nptr);

        nptr.setLinkPrev(end);
        nptr.setLinkNext(start);

        start.setLinkPrev(nptr);

        end = nptr;
    }
    else
    {
        tmp = start;
        ptr = start.getLinkNext();

        while (ptr != null)
        {
            if (val2 <= tmp.getData2() && val2 >= ptr.getData2())
            {
                tmp.setLinkNext(nptr);
                nptr.setLinkPrev(tmp);
                nptr.setLinkNext(ptr);

                ptr.setLinkPrev(nptr);
                ins = true;

                break;
            }
            else
            {
                tmp = ptr;
                ptr = ptr.getLinkNext();
            }
        }
        if (!ins)
        {
            tmp.setLinkNext(nptr);
            nptr.setLinkPrev(tmp);
        }
    }
    size++;
}

在这个例子中,我不知道如何将 2x^3 + 5x^3 节点 简化为 一个节点 7x^3不破坏顺序。

p1.setCoef(2, 3);
p1.setCoef(5, 3);

这个例子应该是5x^8+5x^7+5x^6。

p1.setCoef(3, 6);
p1.setCoef(5, 7);
p1.setCoef(2, 6);
p1.setCoef(5, 8);

我的toString方法也没有问题

等待您的帮助,在此先感谢!

最好用TreeMap代替Circular Linked List

public class Polynomial {

    private final TreeMap<Integer, Integer> map = new TreeMap<>();

    public void setCoef(int coeff, int exp) {
        Integer oldCoeff = map.get(exp);
        if (oldCoeff == null) oldCoeff = 0;
        map.put(exp, oldCoeff + coeff);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Entry<Integer, Integer> e : map.descendingMap().entrySet())
            sb.append("+").append(e.getValue()).append("x^").append(e.getKey());
        return sb.substring(1);
    }

    public static void main(String[] args) {
        Polynomial p1 = new Polynomial();
        p1.setCoef(3, 6);
        p1.setCoef(5, 7);
        p1.setCoef(2, 6);
        p1.setCoef(5, 8);
        System.out.println(p1); // -> 5x^8+5x^7+5x^6
    }
}