Java第15天——链队列

1 Node 类以前是 LinkdedList 的内嵌类, 这里重写了一遍. 访问控制的事情以后再说.
2 为方便操作, 空队列也需要一个节点. 这和以前的链表同理. 头节点的引用 (指针) 称为 header.
3 入队仅操作尾部, 出队仅操作头部.

代码

package datastructure.list;

public class LinkedQueue {
	/**
	 * @author GDY
	 * @date 2021-12-22 04:53:51
	 */
	// 内部类
	class Node {
		int data;
		Node next;

		//构造方法
		public Node(int paraValue) {
			data = paraValue;
			next = null;
		}
	}

	//头指针
	Node header;
	//尾指针
	Node tail;

	//构造一个空队列
	public LinkedQueue() {
		header = new Node(-1);
		// header.next=null;
		tail = header;
	}

	// 入队
	public void enquene(int paraValue) {
		Node tempNode = new Node(paraValue);
		tail.next = tempNode;
		tail = tempNode;
	}

	// 出队
	public int dequeue() {
		if (header == tail) {
			System.out.println("队列中已经没有元素了");
			return -1;
		}
		
		int resultValue = header.next.data;
		
		header.next = header.next.next;
		// 当队列为空时
		
		if (header.next == null) {
			tail = header;
		}
		return resultValue;
	}

	// 重写toString方法
	public String toString() {
		String resultString = "";
		
		if (header.next == null) {
			return "empty";
		}
		
		Node tempNode = header.next;
		while (tempNode != null) {
			resultString += tempNode.data + ",";
			tempNode = tempNode.next;
		}
		
		return resultString;
	}

	public static void main(String[] args) {
		LinkedQueue tempQueue = new LinkedQueue();
		System.out.println("最开始队列为:" + tempQueue.toString());

		for (int i = 0; i < 5; i++) {
			tempQueue.enquene(i + 1);
		}
		System.out.println("入队,队列为:" + tempQueue.toString());

		tempQueue.dequeue();
		System.out.println("出队,队列为:" + tempQueue.toString());

		int tempValue;
		for (int i = 0; i < 5; i++) {
			tempValue = tempQueue.dequeue();
			System.out.println("循环删除" + tempValue + ",新队列为:" + tempQueue.toString());
		}

		for (int i = 0; i < 3; i++) {
			tempQueue.enquene(i + 10);
		}
		System.out.println("入队,队列为:" + tempQueue.toString());
	}

}

运行结果

最开始队列为:empty
入队,队列为:1,2,3,4,5,
出队,队列为:2,3,4,5,
循环删除2,新队列为:3,4,5,
循环删除3,新队列为:4,5,
循环删除4,新队列为:5,
循环删除5,新队列为:empty
队列中已经没有元素了
循环删除-1,新队列为:empty
入队,队列为:10,11,12,

在下觉得声明的这个类使用泛型<E>会更好一点,之后会完善以下并给出代码 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值