用java实现队列结构_Java实现队列——队列内部使用链式存储结构

Java实现队列——队列内部使用链式存储结构

链队列

A153702007-100049.png

代码:

package hash;

/**

* Created with IntelliJ IDEA.

* User: ASUS

* Date: 14-9-17

* Time: 上午11:58

* To change this template use File | Settings | File Templates.

*/

public class CustomLinkQueue {

//定义一个内部类Node,Node实例代表链栈的节点。

private class Node {

//保存节点的数据

private E data;

//指向下个节点的引用

private Node next;

//无参数的构造器

public Node() {

}

//初始化节点的数据域

private Node(E data) {

this.data = data;

}

//初始化全部属性的构造器

public Node(E data, Node next) {

this.data = data;

this.next = next;

}

}

private Node front;  //头指针指向头结点

private Node rear;   //尾节点

private int count; //该队列元素的数量

/**

* 初始化队列

* 此时队列为空

*/

public CustomLinkQueue() {

Node p = new Node();

p.data = null;

p.next = null;

front = rear = p;

}

/**

* 在队列的后端插入节点

*

* @param item

*/

public void enqueue(E item) {

Node newNode = new Node();

newNode.data = item;

newNode.next = null; //入队的节点没有后继节点

this.rear.next = newNode; //让原来的尾节点的后继节点指向新节点

this.rear = newNode;     //rear指向最后一个节点

count++;

}

/**

* 出队

* 在队列的前端删除节点

*

* @return

*/

public E dequeue() throws Exception {

if (isEmpty()) {

throw new Exception("队列为空");

} else {

E obj;

Node p = this.front.next;  //指向队头的第一个节点

obj = p.data;

this.front.next = p.next;

if (rear == p) {

rear = front;

}

count--;

return obj;

}

}

/**

* @return

*/

public int size() {

return count;

}

/**

* 遍历算法

* 移动front指针,直到front指针追上rear指针

*/

public void traverse() {

for (Node current = front.next; current != null; current = current.next) {

System.out.println(current.data);

}

}

/**

* 判断队列为空的条件是front == rear

*

* @return

*/

public boolean isEmpty() {

return front == rear;

}

public static void main(String args[]) throws Exception {

CustomLinkQueue linkQueue = new CustomLinkQueue();

for (int i = 0; i 

linkQueue.enqueue("lyx" + i);

}

System.out.println(linkQueue.size());

System.out.println("===========traverse===========");

linkQueue.traverse();

System.out.println("==============================");

linkQueue.dequeue();

linkQueue.dequeue();

System.out.println("===========traverse===========");

linkQueue.traverse();

System.out.println("==============================");

System.out.println(linkQueue.size());

}

}

====EN====

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值