在Java中创建两个单独的链接列表时出错



我将执行从用户处获得的两个独立多项式的加法、乘法和打印操作。然而,当在main类中创建两个链表时,我添加到第一个链表的节点被添加到第二个链表的节点所取代。我怎么解决这个问题?

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: ");
coefficient = scn.nextInt();
degree = scn.nextInt();
ml.insertLast(coefficient, degree);
//System.out.println(ml.toString());
while (true) {
if (coefficient != 0) {
coefficient = scn.nextInt();
degree = scn.nextInt();
ml.insertLast(coefficient, degree);
} else {
break;
}
}
//System.out.println(ml.toString());
ml2 = new MyLinkedList();
System.out.println("Enter the coefficient and power of the second polynomial. Type 0 at the end: ");
coef = scn.nextInt();
deg = scn.nextInt();
ml2.insertLast(coef, deg);
//System.out.println(ml2.toString());
while (true) {
if (coef != 0) {
coef = scn.nextInt();
deg = scn.nextInt();
ml2.insertLast(coef, deg);
} else {
break;
}
}
}
}
public class MyLinkedList {
static Node first;
static Node last;
static int size = 0;
public MyLinkedList() {
first = null;
last = null;
size = 0;
}
public static 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;
}
}

在你的LinkedList类中声明你的节点"first"one_answers";last"是静态的。这意味着两个linkedlist共享相同的第一个和最后一个。如果它们保持静态,你就不能有一个单独的链表。

最新更新