利用java通过循环单链表设计队列的代码怎么写
时间: 2024-04-29 12:26:42 浏览: 86
用循环链表实现队列操作
以下是利用Java通过循环单链表设计队列的代码:
```
public class Queue {
private Node front; //队头
private Node rear; //队尾
private int size; //队列大小
//定义节点类Node
private class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
}
}
/**
* 判断队列是否为空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 获取队列大小
*/
public int getSize() {
return size;
}
/**
* 入队
*/
public void enqueue(Object obj) {
Node node = new Node(obj);
if(isEmpty()){
front = node;
rear = node;
rear.next = front; //队尾指向队头
}else{
rear.next = node;
rear = node;
rear.next = front; //队尾指向队头
}
size++;
}
/**
* 出队
*/
public Object dequeue() {
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
Object obj = front.data;
if(size == 1){
front = null;
rear = null;
}else{
front = front.next;
rear.next = front; //队尾指向队头
}
size--;
return obj;
}
}
```
阅读全文