链表实现两个整数的乘法算法(Java)

无从下手,三位数和三位数相乘是一个规律,三位数和两位数相乘就变了

import java.util.Scanner;
public class Dolynomial {
    private Node first;
    private Node last;
    private int N;

    private class Node{
        int coef;
        int expo;
        Node next;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    public void enqueue(int coef, int expo) {
        Node oldlast = last;
        last = new Node();
        last.coef = coef;
        last.expo = expo;
        last.next = null;
        if(N == 0) {
            first = last;
        } else
            oldlast.next = last;
        N++;
    }

    //读入一个多项式
    public static Dolynomial read() {
        Dolynomial temp = new Dolynomial();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入整数:");
        int coef = sc.nextInt();
        temp.enqueue(coef, 1);
        return temp;
    }

    public Dolynomial multi(Dolynomial D1, Dolynomial D2) {
        Dolynomial temp = new Dolynomial();
        Node node1 = D1.first;
        Node node2 = D2.first;

        int n1 = D1.size();
        int n2 = D2.size();

        while(n2-- > 0) {
            temp.enqueue(node1.coef * node2.coef, node1.expo + node2.expo);
            node2 = node2.next;
        }

        while(--n1 > 0) {
            Node node3 = temp.first;
            node1 = node1.next;
            node2 = D2.first;
            n2 = D2.size();

            while(n2 > 0) {
                //System.out.println("这个也一样哦!");
                int c = node1.coef * node2.coef;
                int e = node1.expo + node2.expo;
                while(node3.next != null && node3.next.expo > e)
                    node3 = node3.next;
                if(node3.next != null && node3.next.expo == e) {
                    //指数相等,直接相加
                    node3.next.coef += c;
                    if(node3.next.coef == 0) {
                        node3 = node3.next.next;
                    }
                } else {
                    //插入节点
                    Node p = new Node();
                    p.coef = c;
                    p.expo = e;
                    p.next = node3.next;
                    node3.next = p;
                    temp.N++;
                }

                n2--;
                node2 = node2.next;
            }
        }
        return temp;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        Dolynomial d1, d2, result1, result2;
        d1 = read();
        d2 = read();
        result2 = d1.multi(d1, d2);
        Node temp2 = result2.first;
        for (; temp2 != null; temp2 = temp2.next) {
            System.out.println("结果:"+temp2.coef);
        }
    }
}

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632