Add and Print new Nodes

I was working on a program to add nodes to a list, but I seem to be doing something wrong…

My java program has three Classes; Demo, Lista and Node

Class Node:

public class Node {
    
    private int num;
    private Node tail;
    private Node head; 

    public Node (int num, Node head, Node tail) {
        this.num = num;
        this.head = head;
        this.tail = tail;
    }
}

Class Lista:

public class Lista {
    
    private Node nil;
    
    public Lista () {
        nil = null;
    }
    
    public void add (int num) {
        Node newNode = new Node(num, head, tail);
        
        if (head == null) {
            head = newNode;
            tail = newNode;
        }
    }
    
    public void display () {
        Node current = head;
        
        while(current != null) {
            System.out.print(current.num);
        }
    }
}

Class Demo:

public class Demo {
    
    public static void main ( String [] args) {
        Lista lista = new Lista();
        lista.add(3);
        lista.add(9);
        lista.add(7);
        lista.display();
    }
}

Demo class is to add the different nodes to the list "lista". Class Node has num, head which is the next one and tail which is the previous one. How can I go about getting Class Lista to be able to use head and tail from Class Node? And if it is possible would this code work when running Demo? What should I change/modify to get this to work?

>Solution :

You may want to modify your code something like this:

class Node {
    int num;
    Node prev;
    Node next;

    Node(int num) {
        this.num = num;
    }

    Node(int num, Node prev, Node next) {
        this.num = num;
        this.prev = prev;
        this.next = next;
    }

    void setPrev(Node prev) {
        this.prev = prev;
    }

    void setNext(Node next) {
        this.next = next;
    }
}


class Lista {
    Node root;
    Node endNode;

    public void add(int num) {
        Node n = new Node(num);

        if (root == null) {
            root = n;
        } else {
            n.setPrev(endNode);
            endNode.setNext(n);
        }
        endNode = n;
    }

    public void display() {
        Node iterateeNode = root;

        while (iterateeNode != null) {
            System.out.print(iterateeNode.num + " ");
            iterateeNode = iterateeNode.next;
        }
    }
}

Leave a Reply