Java如何将Node链表存储的多项式内容拼接为表达式单行输出
问题描述
我是Java开发初学者,当前需要将存储在Node节点链表中的Termo项内容,拼接为类似5x^3 + 2x^4格式的多项式等式,最终在同一行打印输出。我已实现的Node类、Termo类代码如下,目前编写的escrevePolinomio方法会每行输出一个项,无法满足单行输出的需求,请问该如何调整实现?
现有代码
Node类
public class Node { private Termo element; private Node next; public Node(){ element = null; next= null; } public Node( Termo element, Node next){ this.element= element; this.next= next; } public void setnext( Node next){ this.next= next; } public Node getnext(){ return proximo; } public void setElement( Termo element){ this.element= element; } public Termo getElement(){ return element; } @Override public String toString(){ return "Termo: " + getElement().getCoef() + "x^" +getElement().getExp(); } }
Termo类
private double coef; private int exp; public Termo() { coef=0; exp=0; } public Termo(double coef, int exp) { this.coef = coef; this.exp = exp; } public double getCoef() { return coef; } public void setCoef(int coef) { this.coef = coef; } public int getExp() { return exp; } public void setExp(int exp) { this.exp = exp; } public Object getObject(){ Termo obj = new Termo(this.coef, this.exp); return obj; } @Override public String toString() { return coef + " " + exp; }
现有打印方法
public void escrevePolinomio (Node lista){ if(lista != null){ System.out.println(lista.getElement().getCoef()+"x^"+lista.getElement().getExp()); lista=lista.getnext(); escrevePolinomio(lista); } }
解决方案
问题原因
- 你使用的
System.out.println()方法会在输出内容末尾自动追加换行符,是导致每个项单独占一行的直接原因。 - 现有递归逻辑是每遍历一个节点就直接打印,没有做字符串拼接,也没有处理项之间的
+分隔符,不符合多项式的格式要求。 - 额外注意:你的Node类中
getnext()方法返回的proximo是未定义变量,运行会报错,需要先修正为返回next属性。
代码修正
修复Node类的错误
// 修正getnext方法 public Node getnext(){ return next; }
调整打印方法
这里提供两种实现方式,可按需选择:
1. 递归实现(匹配你原有的递归写法)
通过辅助方法先把所有项拼接为完整的多项式字符串,最后统一一次性打印:
public void escrevePolinomio(Node lista) { System.out.println(montaPolinomio(lista)); } private String montaPolinomio(Node node) { if (node == null) { return "0"; // 空链表默认返回0,可按需调整 } Termo termo = node.getElement(); String termoStr = termo.getCoef() + "x^" + termo.getExp(); if (node.getnext() != null) { return termoStr + " + " + montaPolinomio(node.getnext()); } return termoStr; }
2. 迭代实现(更稳定,避免长链表递归栈溢出)
用StringBuilder拼接所有内容,性能更好,逻辑也更易懂:
public void escrevePolinomio(Node lista) { if (lista == null) { System.out.println("0"); return; } StringBuilder sb = new StringBuilder(); Node current = lista; while (current != null) { Termo termo = current.getElement(); sb.append(termo.getCoef()).append("x^").append(termo.getExp()); if (current.getnext() != null) { sb.append(" + "); } current = current.getnext(); } System.out.println(sb.toString()); }
可选优化
你可以直接修改Termo类的toString方法,直接返回多项式项的格式,后续拼接时不需要重复写拼接逻辑:
@Override public String toString() { return coef + "x^" + exp; }
修改后拼接的时候直接调用termo.toString()即可。
内容的提问来源于stack exchange,提问作者Miguel Rodrigues
相关产品推荐
相关产品推荐

