0

In my main method, when I create an empty SLList, and I call the addLast_iterative() method, if I try to create a reference to the null instance variable 'first' (within addLast_iterative()), then try to reference a new node with the corresponding value, it doesn't change the previous reference 'first' to reference the new IntNode object? I have gotten it to work, but am curious why this doesn't change 'first' to reference to newly created IntNode object. You can skip ahead to addLast_iterative(int x) if this is unclear. I commented out the part that doesn't work, the top "if" loop does work. In other words, "first" still will reference Null, if I use the 'if' statement I commented out. Thanks

public class SLList {

    private static class IntNode {
        public int item;
        public IntNode next;

        public IntNode(int i, IntNode n) {
            this.item = i;
            this.next = n;
        }
    }

    private IntNode first;
    private int size;


    /* initialize empty SLList */
    public SLList() {
        this.first = null;
        this.size = 0;
    }

    public SLList(int x) {
        this.first = new IntNode(x, null);
        this.size = 1;
    }

    public void addFirst(int x) {
        this.first = new IntNode(x, this.first);
        size += 1;
    }

    public int getFirst() {
        return this.first.item;
    }

    /*************************************************************/
    public void addLast_iterative(int x) {

        this.size += 1;

        if (this.first == null) {
            this.first = new IntNode(x, null);
            return;
        }

        IntNode p = this.first;

        // why does this bottom 'if' statement not work, but the top 
        //does?
        /*if (p == null) {
            p = new IntNode(x, null);
            return;
        }*/

        while(p.next != null) {
            p = p.next;
        }
        p.next = new IntNode(x, null);
    }

    /*************************************************************/


    /*************************************************************/
    public int size() {
        return size;
    }
    /*************************************************************/

    public static void main(String[] args) {
        SLList lst = new SLList();
        lst.addLast_iterative(3);
    }
}
nunya
  • 1

1 Answers1

-1

In commented lines you are assigning new object to the reference variable "p" and this.first is still null.

Morteza Adi
  • 2,413
  • 2
  • 22
  • 37