用链表自定义实现一个队列,包括入队,出队,弹出队首元素,队列是否为空功能
class Node<T>{
public T val;
public Node<T> next;
public Node(T val){
this.val = val;
}
}
public class MyQueue<T>{
public Node<T> first;//队头
public Node<T> last;//队尾
//入队
public boolean offer(T val){
Node<T> node = new Node<T>(val);
if (this.first == null){
this.first = node;
this.last = node;
}else{
this.last.next = node;
this.last = node;
}
return true;
}
//出队
public T poll(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
T res = this.first.val;
if (this.first.next==null){
this.last = null;
}
this.first = this.first.next;
return res;
}
//弹出队首元素
public T peek(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
return this.first.val;
}
//判断队列是否为空
public boolean isEmpty(){
if (this.last == this.first && this.first == null){
return true;
}
return false;
}
}
来看看测试:
public class TestDemo2 {
public static void main(String[] args) {
MyQueue<String> myQueue = new MyQueue<>();
myQueue.offer("Java");
myQueue.offer("C++");
System.out.println(myQueue.peek());
myQueue.poll();
myQueue.poll();
System.out.println(myQueue.peek());
}
}
符合预期结果。
用数组实现一个循环队列,包括入队,出队,拿到队首元素,拿到队尾元素,判断队列是否为空,是否为满功能。
public class MyCircularQueue<T> {
private int front;//队头下标
private int rear;//队尾下标
private T[] elem;
public MyCircularQueue(int k){ //k代表存入元素的个数
this.elem = (T[])new Object[k+1]; //这里初始化的时候一定要创建k+1大小的数组,因为会牺牲一个位置来判断队列是否为满
this.front = 0;
this.rear = 0;
}
//入队
public boolean enQueue(T val){
if (isFull()){
return false;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1)%this.elem.length;
return true;
}
//出队
public boolean deQueue(){
if (isEmpty()){
return false;
}
this.front = (this.front+1)%this.elem.length;
return true;
}
//拿到队首元素
public T Front(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
T res = this.elem[this.front];
return res;
}
//拿到队尾元素
public T Rear(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
int index = 0; //定义一个下标,用来判断不同情况
if (this.rear == 0){
index = this.elem.length-1;
}else{
index = this.rear-1;
}
return this.elem[index];
}
//判断队列是否为满
public boolean isFull(){
return (this.rear+1)%this.elem.length == this.front;
}
//判断队列是否为空
public boolean isEmpty(){
return this.front == this.rear;
}
}
来看看测试:
public class TestDemo3 {
public static void main(String[] args) {
MyCircularQueue<Integer> myCircularQueue = new MyCircularQueue<>(3);
myCircularQueue.enQueue(1);
myCircularQueue.enQueue(2);
myCircularQueue.enQueue(3);
System.out.println(myCircularQueue.Front());
System.out.println(myCircularQueue.Rear());
myCircularQueue.deQueue();
myCircularQueue.deQueue();
myCircularQueue.deQueue();
System.out.println(myCircularQueue.Front());
}
}
符合预期结果。