user2775042
user2775042

Reputation: 509

Adding an object to the end of the circular list

I have a working code here which adds a new node to the end. but for some reason after adding the third node, the first node disappears.

This is the method

public boolean add(Token obj)  {

    if(obj == null){
        return false;
    }

    if (head == null){
        head = new Node(null, null, obj);
        return true;
    }

    while (head.next != null){
        head = head.next;
    }
    head.next = new Node(null,null,obj); // Next, Previous , Object

    return true;

}

with creating a new node this

and when i call it from main like this

public static void main(String[] args) {

    CircularList test = new CircularList();

    Token something = new Token("+");
    test.add(something);
    test.add(new Token(2));
    test.add(new Token(5));



    System.out.println(test.toString());


}

}

and my output is

"List contains 2 , 5 "

So if i delete the third add new token ie Token(5), the first one comes back up.

Any help on this? thanks in advance

Upvotes: 0

Views: 253

Answers (1)

codework
codework

Reputation: 66

while (head.next != null){
    head = head.next;
}

It's wrong.U change the head pointer..

Node temp=head;
while(temp.next!=null)
    temp=temp.next
temp.next=new Node(null,null,obj);

Upvotes: 1

Related Questions