Java创建两个独立链表时数据被覆盖的问题求解
链表节点被覆盖的问题修复
核心原因
你的MyLinkedList类中,first、last、size这些成员变量,以及insertLast方法都用了static修饰。static成员是类共享的,所有MyLinkedList实例都会共用这一套数据。当你创建第二个实例ml2时,构造函数会把first、last重置为null,直接覆盖了第一个实例ml的链表内容,导致第一个多项式的节点丢失。
修复方案
1. 移除所有static修饰符
把类里的static关键字全部去掉,让每个实例拥有自己独立的链表指针和状态:
public class MyLinkedList { Node first; Node last; int size = 0; public MyLinkedList() { first = null; last = null; size = 0; } public void insertLast(int x,int y) { Node newNode = new Node(x,y); if (first == null) { first = newNode; last = newNode; } else { last.next = newNode; last = newNode; } size++; } public String toString() { Node tmp = first; String str = ""; while (tmp != null) { str += tmp.coef + "x^"+ tmp.power + "->"; tmp = tmp.next; } return str; } }
2. 修正输入循环的逻辑漏洞
原代码中,当输入系数为0时,依然会执行一次插入操作(把0系数项加入链表),然后才退出循环。调整后的循环可以避免插入无效项:
public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int coefficient, degree; int coef, deg; MyLinkedList ml, ml2; ml = new MyLinkedList(); System.out.println("Enter the coefficient and power of the first polynomial. Type 0 at the end: "); while (true) { coefficient = scn.nextInt(); if (coefficient == 0) { break; } degree = scn.nextInt(); ml.insertLast(coefficient, degree); } ml2 = new MyLinkedList(); System.out.println("Enter the coefficient and power of the second polynomial. Type 0 at the end: "); while (true) { coef = scn.nextInt(); if (coef == 0) { break; } deg = scn.nextInt(); ml2.insertLast(coef, deg); } // 可添加打印、加法、乘法操作,示例: System.out.println("第一个多项式:" + ml); System.out.println("第二个多项式:" + ml2); } }
修改完成后,两个链表实例会各自维护独立的节点数据,不会再出现覆盖问题,后续即可正常实现多项式的加法、乘法操作。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

