数据结构(三):队列Queue简介及其Java实现

本文深入探讨了队列数据结构的实现方式,包括基于链表和数组的两种主要实现方法。详细介绍了基于链表实现队列的具体代码,包括节点定义、初始化、入队、出队等操作,并提供了迭代器实现,便于理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列是先进先出。其实现可以采用链表实现,也可以采用数组实现。基于数组的实现较为麻烦,需要考虑下标回绕的问题。

基于链表的实现

import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * 先进先出队列,基于单向链表的实现
 * @author lm
 *
 * @param <Item>
 */
public class Queue<Item> implements Iterable<Item> {
	
	private Node<Item> first; // beginning of queue
	private Node<Item> last; // end of queue
	private int n; // number of elements on queue

	// helper linked list class
	private static class Node<Item> {
		private Item item;
		private Node<Item> next;
	}

	/**
	 * Initializes an empty queue.
	 */
	public Queue() {
		first = null;
		last = null;
		n = 0;
	}
	
	public boolean isEmpty() {
		return first == null;
	}
	
	public int size() {
		return n;
	}
	
	/*
	 * first is the first one to enqueue
	 * last is the last one to enqueue
	 */
	public void enqueue(Item item) {
		Node<Item> node = new Node<Item>();
		node.item = item;
		if(this.isEmpty()) {
			last = node;
			first = node;
		} else {
			last.next = node;
			last = node;
		}
		n++;
	}
	
	public Item dequeue() {
		if(this.isEmpty())
			throw new NoSuchElementException();
		Item item = first.item;
		first = first.next;
		n--;
		if(this.isEmpty())
			last = null;
		return item;
	}
	
	
	@Override
	public Iterator<Item> iterator() {
		return new Iterator<Item>() {
			private Node<Item> current = first;
			
			@Override
			public boolean hasNext() {
				return current != null;
			}

			@Override
			public Item next() {
				if(!hasNext())
					throw new NoSuchElementException();
				Item item = current.item;
				current = current.next;
				return item;
			}
		};
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值