Implementing queue in java

后端 未结 3 2026
攒了一身酷
攒了一身酷 2021-01-29 14:16

Implementing a queue in Java is pretty common interview question. I surfed online and saw many implementations where they do fancy stuff like implementing queue interface and wr

3条回答
  •  一整个雨季
    2021-01-29 14:35

    One way is to maintain an array of items q and two indices to the head and the tail of the queue (initially set to 0). Pseudo-code follows:

    enqueue(x)
    {   q[tail++] = x;
    }
    
    dequeue()
    {   return q[head++];
    }
    

    If the array overflows, you double the size and reinsert the items. This yields O(1) amortized time per operation. Another approach is to use a linked list (which you should implement) and again store a pointer to the head and a pointer to the tail.

提交回复
热议问题