用数组实现队列,详细代码如下:
package stack;
public class QueueByArray {
String[] arrays;
int count;
int head;
int tail;
public QueueByArray(int n){
arrays = new String[n];
count = n;
}
public boolean enqueue(String item){
if (tail == count) {
return false;
}
arrays[tail] = item;
tail++;
return true;
}
public String dequeue(){
if (head == tail) {
return null;
}
String temp = arrays[head];
head++;
return temp;
}
public boolean empty(){
return head == tail;
}
}
复杂度分析
时间复杂度 : enqueue 和 dequeue 均为:O(1)
空间复杂度 : enqueue 和 dequeue 均为:O(1)
网友评论