您的位置:首页 > 编程语言 > Java开发

一元多项式求和(Java链表实现)

2015-04-08 14:31 337 查看
package com.polyn_sum;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

class Polyn {

public float coef;//系数

public int expn;//指数

}

class LNode {

Polyn polyn;

LNode next;



public static String show(LNode p){

return (p.polyn.coef+","+p.polyn.expn);

}





public static LNode createList(int num) throws IOException {

LNode head = new LNode();

LNode p = null;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

for (int i = 0; i < num; ++i) {

LNode q = new LNode();

String[] xx = br.readLine().split(",");

//System.out.println("xx[0]"+xx[0]+",xx[1]"+xx[1]);

q.next = null;

q.polyn = new Polyn();

q.polyn.coef = Float.valueOf(xx[0]);

q.polyn.expn = Integer.valueOf(xx[1]);

if (i == 0) {

head.next = q;

} else {

p.next = q;

}

p = q;

}

return head;

}

/**

* 比较指数之和

* @param qa

* @param qb

* @return

*/

public static int cmp(LNode qa, LNode qb){

if(qa.polyn.expn < qb.polyn.expn)

return -1;

else if(qa.polyn.expn == qb.polyn.expn)

return 0;

else

return 1;

}

}





package com.polyn_sum;

import java.io.IOException;

public class Sum {

public static void main(String[] args) {

try {

LNode Alist = LNode.createList(3);

LNode Blist = LNode.createList(4);

Alist = AddPolyn(Alist, Blist);

LNode p = Alist.next;

while(p != null){

System.out.println(p.polyn.coef+","+p.polyn.expn);

p = p.next;

}

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 多项式相加(ok)

*/

public static LNode AddPolyn(LNode Alist, LNode Blist) {

LNode ha = Alist;//头结点

LNode hb = Blist;//头结点

LNode qa = Alist.next;//第一项

LNode qb = Blist.next;//第一项



while (qa!= null && qb != null) {

System.out.println("当前比较:"+LNode.show(qa)+"<>"+LNode.show(qb));

switch (LNode.cmp(qa, qb)) {

case -1:

ha = qa;

qa = qa.next;

//System.out.println("qa < qb");

break;

case 0:

float sum = qa.polyn.coef + qb.polyn.coef;//求系数和

if (sum != 0f) {

qa.polyn.coef = sum;//不等于0,合并

ha = qa;

qa = qa.next;

//释放qb

hb.next = qb.next;

qb = null;

qb = hb.next;

//System.out.println("qa + qb != 0");

} else {

ha.next = qa.next;// 等于0,删除当前节点

qa = null;

qa = ha.next;

hb.next = qb.next;

qb = null;

qb = hb.next;

//System.out.println("qa + qb = 0");

}

break;

case 1:

hb.next = qb.next;

qb.next = ha.next;

ha.next = qb;

ha = qb;

qb = hb.next;

//System.out.println("qa > qb");

break;

}

}



if(qb != null){

ha.next = qb;

}



return Alist;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: