Home > Back-end >  Getting an error when creating two separate linkedlists in Java
Getting an error when creating two separate linkedlists in Java

Time:11-17

I will do the addition multiplication and print operations of two separate polynomials that I will get from the user. However, when creating two linkedlists in the main class, the nodes that I added to the first linkedlist are replaced by the nodes that I added to the second linkedlist. How can I solve this?

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;
    }
}

CodePudding user response:

Inside your LinkedList class you declare your Nodes "first" and "last" as static. This means that both LinkedLists share the same first and last. You wont be able to have a separate linked list if they remain static.

  • Related