当前位置:   article > 正文

Java-队列的基本操作_java队列的使用

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());
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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

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;
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号