joeymed joeymed - 21 days ago 9
Java Question

Singly Linked Lists of Intergers

I need to make a singly-linked list for my array of integers, but, I don't know what is currently wrong with my code right now.

This is the code to create the nodes. (the data)

package sllset;

class SLLNode {
int value;
SLLNode next;

public SLLNode(int i, SLLNode n){
value = i;
next = n
}
}


My other class which has my methods and constructors look like this.

package sllset;


public class SLLSet {
private int setSize;
private SLLNode head;

public SLLSet(){
head = null;
setSize = 0;
}

public SLLSet(int[] sortedArray){ //second constructor
setSize = sortedArray.length;
int i;
head=null;
for(i=0;i<setSize;i++){
head.next = head;
head = new SLLNode(sortedArray[i],head.next);
}
}


public String toString(){
SLLNode p;
String result = new String();
for(p=head ; p!=null ; p=p.next)
result += p.value;
return result;
}

public static void main(String[] args) {
int[] A = {2,3,6,8,9};
SLLSet a = new SLLSet(A);
System.out.println(a.toString());

}

}


My problem is that my second constructor doesn't work and I dont really have a clue as to why. I have been following a guide on how to make most of these functions so my knowledge of the code I guess isn't great enough to decipher the problem.

EDIT: So someone told me to specify the problem which I get a NULLPointerException at line 19; where I code head.next = head; . However, when
I remove that part to test, line 20 gets the error message

Answer

Let's look at this

head=null;     // you are setting head to null
for(i=0;i<setSize;i++){
    head.next = head;  // see two lines up, head is null, it can not have next

Your constructor has some problems. Try using this version:

public SLLSet(int[] sortedArray){ //second constructor
    head = null;
    if (sortedArray == null || sortedArray.length == 0) {
        setSize = 0;
    }
    setSize = sortedArray.length;
    head = new SLLNode(sortedArray[0], null);
    SLLNode curr = head;

    for (int i=1; i < setSize; ++i) {
        curr.next = new SLLNode(sortedArray[i], null);
        curr = curr.next;
    }
}