1

I am trying to insert items circularly in a queue.. i have the following code but it doesn'n insert them right. what's the problem?

public boolean insert(int element){
    if ( head == -1 && tail == -1 ){
        head = 0;
        tail = 0;
        elements[tail] = element;
        return true;
    }  
    else if((tail+1)%capacity == head) {
        System.out.println("Full");
        return false;
    }
    else {
        tail = (tail+1)%capacity;
        elements[tail] = element;
        return true;
    }
}
9
  • Code runs fine for me. Can you specif your problem more precisely? When does the problem occur? What is the expected output? What is the acutual output? Commented Apr 11, 2015 at 17:09
  • for example. i want to insert some elements in this way: for (int i = 0; i < 6; i ++){myQueue.insert(i+1);}. the first element is always null. Commented Apr 11, 2015 at 17:10
  • Can you give a complete example (including main method) please? I doubt that the first element is null since you store primitives. Commented Apr 11, 2015 at 17:15
  • i make a queue with 6 elements. right? and it prints [null,1,2,3,4,5] and the right is [1,2,3,4,5,6].. more specific now? Commented Apr 11, 2015 at 17:20
  • Not really. I cannot reproduce the error. I used your insert method and initialized head and tail with -1. Works fine for me. Commented Apr 11, 2015 at 17:22

1 Answer 1

1
public boolean insert(int element){
    if (getCapacity() == capacity) {
        System.out.println("Queue is full.");
        return false;
    }else {
        elements[tail] = element;
        tail = (tail+1)%capacity;
        n++;
       return true;
    }
}

and

public int getCapacity(){
    return n;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.