java 链式存储 队列_队列的链式存储方式的实现(Java语言描述)

链队列的结构示意图:

0818b9ca8b590ca3270a3433284dd417.png

先进先出。

QueueInterface.java//操作方法接口

package 队列的实现;

public interface QueueInterface {

public void enQueue(Object t);

public Object delQueue();

public int size();

public boolean isEmpty();

public Object head();

public void clear();

}

Node.java//节点类

package 队列的实现;

public class Node {

T data;

Node next;

}

Queue.java//队列的定义和接口实现

package 队列的实现;

public class Queue implements QueueInterface{

Node front,rear;//对头指针,队尾指针

//构造一个空的链队列

public Queue(){

front = new Node();

rear = new Node();

rear = front;

}

//实现接口里的操作

public boolean isEmpty(){

if(front == rear)

return true;

else

return false;

}

public int size(){

int i = 0;

Node p = front.next;

while(p != null){

p = p.next;

i++;

}

return i;

}

public Object head(){

if(this.isEmpty() == false)

return front.next.data;

System.out.println("队列为空,不存在队头元素!");

return 0;

}

public void enQueue(Object obj){

Node p = new Node();

p.data = (T)obj;

rear.next = p;

p.next = null;

rear = p;

}

public Object delQueue(){

T t;

Node p = new Node();

if(this.isEmpty() == true){

System.out.println("队列为空,不能进行删除操作!");

return 0;

}

else{

p = front.next;

front.next = p.next;

if(p.next == null)//出队后队列为空

rear = front;

t = p.data;

p = null;

return t;

}

}

public void clear(){

front = rear;

}

}

TestQueue.java//测试类

package 队列的实现;

public class TestQueue {

public static void main(String[] args) {

Queue queue = new Queue();

for(int i=1; i<=10; i++){

queue.enQueue(i);

}

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

System.out.println(queue.isEmpty());

for(int i=1; i<=10; i++){

System.out.print(queue.delQueue() + " ");

}

System.out.println();

System.out.println(queue.isEmpty());

for(int i=1; i<=10; i++){

queue.enQueue(i);

}

System.out.println(queue.isEmpty());

queue.clear();

System.out.println(queue.isEmpty());

}

}

实现结果:

10 false 1 2 3 4 5 6 7 8 9 10 true false true

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值