java学习第17天,链队列

队列在数据结构中非常基础,尤其是出队和入队的算法很有意思。可以好好看看,多多理解一下

package java11to20;

public class D17_LinkedQueue {
	class Node {
		int data;
		Node next;
		public Node(int par) {
			data = par;
			next = null;
		}
	}

	Node header;
	Node tail;

	public static void main(String[] args) {
		D17_LinkedQueue linkQueue = new D17_LinkedQueue();
		System.out.println("初始化,列表为:" + linkQueue.toString());

		for (int i = 0; i < 7; i++) {
			linkQueue.enqueue(i + 1);// 入队
		}
		System.out.println("入队完毕,队列为:" + linkQueue.toString());

		linkQueue.dequeue();// 出队
		System.out.println("出队完毕,队列为:" + linkQueue.toString());

		int value;
		for (int i = 0; i < 7; i++) {
			value = linkQueue.dequeue();
			System.out.println(String.format("出队值 %s,最新队列为:%s", value, linkQueue.toString()));
		}
	}

	public D17_LinkedQueue() {
		header = new Node(-1);
		header.next = null;
		tail = header;
	}

	public void enqueue(int par) {
		Node node = new Node(par);
		tail.next = node;
		tail = node;
	}

	public int dequeue() {
		if (header.next == null) {
			System.out.println("队空");
			return -1;
		}
		int resultValue = header.next.data;
		header.next = header.next.next;
		return resultValue;
	}

	public String toString() {
		String result = "";

		if (header.next == null) {
			return "空";
		}
		Node node = header.next;
		while (node != null) {
			result += node.data + ",";
			node = node.next;
		}
		return result;
	}
}

输出结果:

初始化,列表为:空
入队完毕,队列为:1,2,3,4,5,6,7,
出队完毕,队列为:2,3,4,5,6,7,
出队值 2,最新队列为:3,4,5,6,7,
出队值 3,最新队列为:4,5,6,7,
出队值 4,最新队列为:5,6,7,
出队值 5,最新队列为:6,7,
出队值 6,最新队列为:7,
出队值 7,最新队列为:空
队空
出队值 -1,最新队列为:空
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值