日撸代码300行学习笔记 Day 17

本文介绍了链队的实现原理,包括入队和出队操作,特别强调了出队时判断队空并重置尾指针的重要性。通过示例代码展示了链队的入队和出队过程,并进行了多轮测试,验证了链队操作的正确性。在实际应用中,链队的操作细节对于避免错误至关重要。
摘要由CSDN通过智能技术生成

1.链队的基本实现

 

在链队进行操作的时候,入队仅能在尾部操作,出队在头部操作。注意在出队时若已空,需要将尾指针重置到头指针的位置去。

2.代码

package demo;

public class LinkedQueue {

	class Node {
		int data;
		Node next;

		// 节点定义
		public Node(int paraValue) {
			data = paraValue;
			next = null;
		}// Of the constructor
	}// Of class Node

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

	// 建立一个空的链表
	public LinkedQueue() {
		header = new Node(-1);
		// header.next = null;  多余的一句??好像重复了啊
		tail = header;
	}// Of the first constructor

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

	/*
	 * ******** 入队 ********
	 */
	public int dequeue() {
		// 越界检查
		if (header == tail) {
			System.out.println("No element in the queue");
			return -1;
		} // Of if

		int resultValue = header.next.data;

		header.next = header.next.next;
		// 如果全部出队
		if (header.next == null) {
			tail = header;
		} // Of if

		return resultValue;
	}// Of dequeue

	/*
	 * ******** 重写toString ********
	 */
	public String toString() {
		String resultString = "";

		if (header.next == null) {
			return "empty";
		} // Of if

		Node tempNode = header.next;
		while (tempNode != null) {
			resultString += tempNode.data + ", ";
			tempNode = tempNode.next;
		} // Of while

		return resultString;
	}// Of toString

	/*
	 * main
	 */
	public static void main(String args[]) {
		LinkedQueue tempQueue = new LinkedQueue();
		System.out.println("Initialized, the list is: " + tempQueue.toString());

		for (int i = 0; i < 5; i++) {
			tempQueue.enqueue(i + 1);
		} // Of for i
		System.out.println("Enqueue, the queue is: " + tempQueue.toString());

		tempQueue.dequeue();
		System.out.println("Dequeue, the queue is: " + tempQueue.toString());

		int tempValue;
		for (int i = 0; i < 5; i++) {
			tempValue = tempQueue.dequeue();
			System.out.println("Looped delete " + tempValue + ", the new queue is: " + tempQueue.toString());
		} // Of for i

		for (int i = 0; i < 3; i++) {
			tempQueue.enqueue(i + 10);
		} // Of for i
		System.out.println("Enqueue, the queue is: " + tempQueue.toString());
	}// Of main
}// Of class LinkedQueue

运行结果: 

 3.总结

链队中一定要注意入队出队的位置,已经入队后哪个指针动的问题。在后面main中经过多次入队出队的测试,在队列元素出队的时候,一定判断是否队空,如果队空了的话,一定要将尾指针回到头指针的位置,否则在循环当中,队空以后还在输出,就出现越界数据出错的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值