Java实现顺序队列
时间: 2024-06-13 20:06:02 浏览: 13
以下是Java实现顺序队列的方法和步骤:
1.定义队列接口IQueue,包含clear()、isEmpty()、length()、peek()、offer()和poll()方法。
2.实现顺序队列ShunxuQueue,实现IQueue接口中的所有方法。
3.提供清空(clear)、判空(isEmpty)、队列长度(length)等方法。
4.提供入队方法:offer。
5.提供出队方法:poll。
6.提供获取队列头部元素的方法:peek。
7.提供实现的完整代码。
以下是Java实现顺序队列的代码示例:
```java
//定义队列接口
public interface IQueue {
void clear();
boolean isEmpty();
int length();
Object peek();
void offer(Object object) throws Exception;
Object poll();
}
//实现顺序队列
public class ShunxuQueue implements IQueue {
private Object[] queue;
private int front;
private int rear;
public ShunxuQueue(int maxSize) {
queue = new Object[maxSize];
front = 0;
rear = 0;
}
@Override
public void clear() {
front = rear = 0;
}
@Override
public boolean isEmpty() {
return front == rear;
}
@Override
public int length() {
return rear - front;
}
@Override
public Object peek() {
if (isEmpty()) {
return null;
}
return queue[front];
}
@Override
public void offer(Object object) throws Exception {
if (length() == queue.length) {
throw new Exception("队列已满");
}
queue[rear++] = object;
}
@Override
public Object poll() {
if (isEmpty()) {
return null;
}
Object object = queue[front];
queue[front++] = null;
return object;
}
}
//测试顺序队列的相应方法
public class TestShunxuQueue {
public static void main(String[] args) throws Exception {
ShunxuQueue queue = new ShunxuQueue(5); queue.offer("A");
queue.offer("B");
queue.offer("C");
System.out.println(queue.poll()); //输出:A
System.out.println(queue.poll()); //输出:B
System.out.println(queue.peek()); //输出:C
System.out.println(queue.length()); //输出:1
queue.clear();
System.out.println(queue.isEmpty()); //输出:true
}
}
//相关问题:
--相关问题--:
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)