Hello,
I wrote an add method but for some reason it does not add more than 3 values. Could anyone tell me why?
here is my method:

public void addValue(int value) {
        IntNode cur = head;
        IntNode prev =  cur;
        IntNode t = new IntNode(value);

        if (value <= cur.data){ // if the value of the new node t is greater then the value of previos node
           
            t.link =head;    
            head =t;
        }
        else{
          while(value > cur.data){
            cur = cur.link;
        }
        t.link = cur;
        prev.link = t;
        }
    
    }

Thank you

IntNode cur = head;
IntNode prev = cur;

Doesn't make any sense. You're essentially assigning cur = head, then prev = head. Do you mean to say:

IntNode prev = cur;
IntNode cur = head;


?????

Where are you adding first node (head)?
If addValue() is suppose to add new nodes then head should also be added in this function. But it seems you are adding is manually something like this:

head = new IntNode(value);

As far as your present code is concerned you are not checking for end of the list and not keeping track of previous node as well in while loop. while loop should look like this:

while(value > cur.data || cur == NULL){
    prev = cur;
    cur = cur.link;
}

Hope you understand these points.

Yeah, it seems like your add method is trying to add a Node in sorted order... instead of just adding it at the end of the list.

Thanks guys

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.