队列接口 IQueue.java
1 package cn.ftf.ILinkQueue; 2 3 public interface IQueue { 4 public void clear(); 5 public boolean isEmpty(); 6 public int length(); 7 public Object peek(); //返回队列首元素 8 public void offer(Object x); //将元素插入队尾 9 public Object pool(); //从队首出队 10 public void display(); //遍历队列元素 11 }经典结点类Node.java
package cn.ftf.ILinkQueue; /** * 节点类 * 单链表节点类描述 * @author 房廷飞 * */ public class Node { public Object data; //存放数据值 public Node next; //存放后继节点 //无参构造函数 public Node() { this(null,null); } //只有结点值的构造参数 public Node(Object data) { this(data,null); } //有结点值和后继结点的构造参数 public Node(Object data, Node next) { super(); this.data = data; this.next = next; } }
链队列的实现类MyLinkQueue.java
1 package cn.ftf.ILinkQueue; 2 3 public class MyLinkQueue implements IQueue{ 4 private Node first; 5 private Node last; 6 7 8 public MyLinkQueue(){ 9 first=last=null; 10 } 11 12 @Override 13 public void clear() { 14 first=last=null; 15 16 } 17 18 @Override 19 public boolean isEmpty() { 20 // TODO Auto-generated method stub 21 return first==null; 22 } 23 24 @Override 25 public int length() { 26 int len=0; 27 if(isEmpty()) { 28 return 0; 29 } 30 Node fir=first; 31 while(fir!=null) { 32 fir=fir.next; 33 len++; 34 } 35 return len; 36 } 37 38 @Override 39 public Object peek() { //返回队首元素 40 return first.data; 41 } 42 43 @Override 44 public void offer(Object x) { //插入队尾 45 Node n=new Node(x); 46 if(isEmpty()) { 47 first=last=n; 48 } 49 last.next=n; 50 last=n; 51 52 } 53 54 @Override 55 public Object pool() { //从队首出队,并返回 56 Node n=first; 57 first=first.next; 58 return n.data; 59 } 60 61 @Override 62 public void display() { 63 if(!isEmpty()) { 64 Node fir=first; 65 while(fir!=null) { 66 System.out.println(fir.data); 67 fir=fir.next; 68 } 69 } 70 } 71 72 public static void main(String[] args) { 73 MyLinkQueue m=new MyLinkQueue(); 74 m.offer("hello"); 75 m.offer("word"); 76 m.offer("!!!"); 77 m.display(); 78 System.out.println("--------------"); 79 m.pool(); 80 m.display(); 81 System.out.println(m.length()); 82 m.clear(); 83 System.out.println("--------------"); 84 m.display(); 85 } 86 87 }
转载于:https://www.cnblogs.com/fangtingfei/p/11312061.html