利用链表实现队列

队列是一种只允许在表的前端进行删除操作,而在表的后端进行插入操作的线性数据结构
我们可以利用链表来实现队列,具体实现代码如下:

import java.util.NoSuchElementException;

/**
 * 用链表实现队列
 * @author Victor Gong
 *
 * @param <Item>	队列中元素类型
 */
public class LinkedQueue<Item> {
	
	private Node first;	//头结点
	private Node last;	//末结点
	private int n;	//队列大小
	
	private class Node{
		private Node next;
		private Item item;
		public Node(Item item) {
			super();
			this.item = item;
		}
	}

	public LinkedQueue() {
		super();
		first = null;
		last = null;
		n = 0;
	}
	
	/**
	 * 
	 * @return	队列的大小
	 */
	public int size() {
		return n;
	}
	
	/**
	 * 
	 * @return	队列是否为空
	 */
	public boolean isEmpty() {
		return n == 0;
	}
	
	/**
	 * 入队列
	 * @param item	要入队列的元素
	 */
	public void enquque(Item item) {
		Node oldLast = last;
		last = new Node(item);
		if (first == null) {
			first = last;
		}else {
			oldLast.next = last;
		}
		last.next = null;
		n++;
	}
	
	/**
	 * 将元素移出队列并返回它的值
	 * @return	出队列的元素
	 */
	public Item dequeue() {
		if (isEmpty()) {
			throw new NoSuchElementException("队列为空");
		}
		Item item = first.item;
		first = first.next;
		n--;
		return item;
	}
	
	/**
	 * 
	 * @return	最新添加到队列的元素
	 */
	public Item peek() {
		if (isEmpty()) {
			return null;
		}
		return first.item;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		StringBuilder s = new StringBuilder();
		for (Node x = first; x != null; x = x.next) {
			s.append(x.item + " ");
		}
		return s.toString();
	}
	
	public static void main(String[] args) {
		LinkedQueue<Integer> queue = new LinkedQueue<Integer>();
		System.out.println(queue.isEmpty());
		queue.enquque(1);
		queue.enquque(2);
		queue.enquque(3);
		queue.enquque(4);
		queue.enquque(5);
		System.out.println(queue.isEmpty());
		System.out.println(queue.toString());
		System.out.println(queue.peek());
		System.out.println(queue.size());
		queue.dequeue();
		System.out.println(queue.toString());
		System.out.println(queue.peek());
		System.out.println(queue.size());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值