码迷,mamicode.com
首页 > 其他好文 > 详细

链表实现多项式相加

时间:2020-06-27 10:09:38      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:col   null   code   function   reac   UNC   his   pre   log   

function Node(coef,expon) {
    this.coef = coef; // 系数
    this.expon = expon; // 指数
    this.next = null;
}
List.attach = function(node) {
    let current = this.head;
    while(current.next) {
        current =  current.next;
    }
    current.next = node;
    return this;
}
List.add = function(list1,list2) {  // 两个多项式 list
    let list_out = new List(), t1 = list1.head, t2 = list2.head;
    console.log(t1,t2);
    let current = list_out.head;
    
    while(t1 && t2) {
        while(current.next) {
            current = current.next;
        }
        current.next =  new Node();
        if(t1.expon == t2.expon) {
            current.next.expon = t1.expon;
            current.next.coef = t1.coef + t2.coef;
            t1 = t1.next;
            t2 = t2.next;
        } else if(t1.expon > t2.expon) {
            current.next.expon = t1.expon;
            current.next.coef = t1.coef;
            t1 = t1.next;
        } else {
            current.next.expon = t2.expon;
            current.next.coef = t2.coef;
            t2 = t2.next;
        }
    }
    
    while(t1) {
        while(current.next) {
            current = current.next;
        }
        current.next =  new Node();
        current.next.expon = t1.expon;
        current.next.coef = t1.coef;
        t1 = t1.next;
    }
    while(t2) {
        while(current.next) {
            current = current.next;
        }
        current.next =  new Node();
        current.next.expon = t2.expon;
        current.next.coef = t2.coef;
        t2 = t2.next;
    }
    list_out.head = list_out.head.next;
    return list_out.head;
}
function List() {
    this.head = new Node();
    this.attach = List.attach;
    this.add = List.add;
}
// 3x^4 - 5x^2 + 6x - 2
// 5x^20 - 7x^4 + 3x
let arr1 = [[3,4],[-5,2],[6,1],[-2,0]]
let list1 = new List();
arr1.forEach((item,index) => {
    list1.attach(new Node(item[0],item[1]))
})
list1.head = list1.head.next;

let arr2 = [[5,20],[-7,4],[3,1]]
let list2 = new List();
arr2.forEach((item,index) => {
    list2.attach(new Node(item[0],item[1]))
})
list2.head = list2.head.next;

let list_out = list1.add(list1,list2);
let result = ‘‘;
while(list_out) {
    if(!result) {
        result += `(${list_out.coef}x^${list_out.expon})`;
    } else {
        result += `+(${list_out.coef}x^${list_out.expon})`;
    }
    list_out = list_out.next;
}
console.log("多项式之和 = " + result);
// 亲测有效,多指教!

 

链表实现多项式相加

标签:col   null   code   function   reac   UNC   his   pre   log   

原文地址:https://www.cnblogs.com/strivegys/p/13197063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!