Marina
Marina

Reputation: 49

Adding in a Sorted Linked List

So I am writing a code for a Sorted LinkedList that stores integers. Integers must be stored in ascending order when added. My code for a Node class has two values and constructors that are not written here because they are obvious.

public class Node {
int value;
Node next;
}

Part of my code for Sorted Linked List is

public class SortedList {

Node head;
public int listCount;


public SortedList(){
    listCount = 0;
    this.head=null;

}



public void add(int num){
    Node newNode= new Node(num);
    Node temp=head;

    if (head==null) {
        head=newNode;
        listCount++;
        System.out.println("Node with data "+num+" was added.");
    }
     else {
        while ((temp.value < num) && (temp.next!=null)) {
            temp = temp.next;
        }
        if (temp.next==null){
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        }
        else {
            newNode.next=temp.next.next;
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        }


    }

}

So when I test my code and add numbers 1,81,63,7,8,9,23 my output is

Node with data 1 was added.Node with data 81 was added. Node with data 63 was added. Node with data 7 was added. Node with data 8 was added. Node with data 9 was added. Node with data 23 was added. 1 -> 81 -> 23 END List Count is 7

So you can see that when I try to show the linked list it is only 1 that points to 81, that points to 23. All other values where lost. I used this code to get output:

      public String toString(){
        Node temp = head;
        while(temp.next!=null){
            System.out.print(temp.value+" -> ");
            temp = temp.next;
        }
        System.out.print(temp.value);
        return " END List Count is "+listCount;

}

Upvotes: 0

Views: 193

Answers (2)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

There are two problems in your implementation. The first one is causing the values to get lost. This problem lies in the assignment -

newNode.next=temp.next.next;

Change it to -

newNode.next=temp.next;

The second one is your while condition check -

(temp.value < num) && (temp.next!=null)

This will destroy the sorted order. Change it to -

(temp.next!=null) && (temp.next.value < num)

Upvotes: 0

dryleaf
dryleaf

Reputation: 423

you made a typo mistake in this line:

newNode.next=temp.next.next;

Please change it to:

newNode.next=temp.next;

Upvotes: 0

Related Questions