Java的链式队列
参考https://www.cnblogs.com/lixiaolun/p/4646312.html
java实现链队列的类代码:
1 package linkqueue; 2 3 public class LinkQueue { 4 5 class Element 6 { 7 Object elem; 8 Element next; 9 } 10 11 private Element front; 12 private Element rear; 13 private Element header = null; 14 15 /** 16 * 初始化队列 17 * */ 18 void initQueue() 19 { 20 header = new Element(); 21 front = new Element(); 22 rear = new Element(); 23 front=header; 24 rear=header; 25 } 26 27 /** 28 * 向队列插入元素 29 * */ 30 void enQueue(Object o) 31 { 32 Element e=new Element(); 33 e.elem=o; 34 if(rear==header)//第一次插入元素 35 { 36 rear=e; 37 header.next=e; 38 front.next=e; 39 }else 40 { 41 rear.next=e; 42 rear=e; 43 } 44 } 45 46 /** 47 * 出队 48 * */ 49 Object deQueue() 50 { 51 Object o = null; 52 if(rear==header) 53 { 54 System.out.println("队列为空!"); 55 }else 56 { 57 o=front.next.elem; 58 if(front.next==rear)//队中只有一个元素 59 { 60 front.next=header; 61 rear=header; 62 }else//队中大于一个元素 63 { 64 front.next=front.next.next; 65 } 66 } 67 return o; 68 } 69 70 /** 71 * 打印队列 72 * */ 73 void print() 74 { 75 System.out.print("打印队列:"); 76 Element temp = front; 77 while(temp!=rear) 78 { 79 System.out.print(temp.next.elem+"\t"); 80 temp=temp.next; 81 } 82 System.out.println(); 83 } 84 }
测试类代码:
1 package linkqueue; 2 3 public class LinkQueueMain { 4 5 public static void main(String[] args) { 6 LinkQueue lQueue = new LinkQueue(); 7 lQueue.initQueue(); 8 System.out.println("出队操作:"+lQueue.deQueue()); 9 lQueue.enQueue(1); 10 lQueue.enQueue(2); 11 lQueue.enQueue(3); 12 lQueue.enQueue(4); 13 lQueue.enQueue(5); 14 lQueue.print(); 15 16 System.out.println("出队操作:"+lQueue.deQueue()); 17 System.out.println("出队操作:"+lQueue.deQueue()); 18 lQueue.print(); 19 20 System.out.println("出队操作:"+lQueue.deQueue()); 21 System.out.println("出队操作:"+lQueue.deQueue()); 22 lQueue.print(); 23 24 System.out.println("出队操作:"+lQueue.deQueue()); 25 System.out.println("出队操作:"+lQueue.deQueue()); 26 lQueue.print(); 27 28 } 29 30 }