Java-队列的基本操作

  • Post author:
  • Post category:java




一、概念

队列是数据结构中比较重要的一种类型(是一种数据结构),它支持 FIFO,尾部添加、头部删除(先进队列的元素先出队列),跟我们生活中的排队类似。

队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。

LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。


注:队列是先进先出,栈是先进后出。



二、Java队列的基本用法(数据结构)

1.offer():入队操作,添加元素

2.poll(): 出队操作,返回队列首元素并删除

3.peek():出队操作,获取队列首元素不删除

4.isEmpty():判断队列是否为空

代码如下(示例):

public class Queue_Exercise {
	public static void main(String args[]) {
		// 创造一个实例对象
		Queue<Integer> queue = new LinkedList<>();
		// 入队操作(尾插法) offer() 添加元素
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);	
		// 出队操作 poll() 返回队首元素并删除
		queue.poll();
		queue.poll();
		// 输出队首元素 peek() 返回队首元素不删除
		System.out.println(queue.peek());
		//判断队列是否为空  isEmpty()
		System.out.println(queue.isEmpty());
	}
}



三、用链表实现自己的队列方法

public class MyQueue {
	private Node firstNode; // 队头
	private Node lastNode; // 队尾

	// 入队(尾插法)
	public void offer(int data) {
		Node cur = new Node(data);
		if (this.firstNode == null) {
			this.firstNode = cur;
			this.lastNode = cur;
		} else {
			this.lastNode.next = cur;
			this.lastNode = cur;
		}
	}

	// 判断队列是否为空
	public Boolean isEmpty() {
		if (this.firstNode == null) {
			return true;
		}
		return false;
	}

	// 出队 获得队首元素并删除
	public int poll() {
		if (isEmpty()) {
			throw new UnsupportedOperationException("队列为空");

		}
		int ret = this.firstNode.data;
		this.firstNode = this.firstNode.next;
		return ret;
	}

	// 获得队首元素但不删除
	public int peek() {
		if (isEmpty()) {
			throw new UnsupportedOperationException("队列为空");
		}
		int ret = this.firstNode.data;
		return ret;
	}

	public static void main(String[] args) {
		MyQueue myQueue = new MyQueue();
		myQueue.offer(1);
		myQueue.offer(2);
		myQueue.offer(3);
		System.out.println(myQueue.peek());
		myQueue.poll();
		System.out.println(myQueue.peek());
	}

}

class Node {
	public int data;
	public Node next;

	public Node(int data) {
		this.data = data;
	}
}



版权声明:本文为qq_51537858原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。