1 //用双端链表实现队列 2 /** 3 * 节点类 4 */ 5 class LinkQ { 6 private long data; 7 public LinkQ next; 8 9 public LinkQ(long d) { 10 this.data = d; 11 } 12 13 public String toString() { 14 return String.valueOf(this.data); 15 } 16 } 17 /** 18 * 双端链表类 19 */ 20 class FirstLastLink { 21 private LinkQ first; 22 private LinkQ last; 23 24 public FirstLastLink() { 25 first = null; 26 last = null; 27 } 28 29 public boolean isEmpty() { 30 return first == null; 31 } 32 33 public void insertLast(LinkQ l) { 34 if (isEmpty()) 35 first = l; 36 else 37 last.next = l; 38 last = l; 39 } 40 41 public LinkQ deleteFirst() { 42 LinkQ temp = first; 43 if (first.next == null) 44 last = null; 45 first = first.next; 46 return temp; 47 } 48 49 @Override 50 public String toString() { 51 if (isEmpty()) 52 return "[]"; 53 LinkQ curr = first; 54 StringBuilder sb = new StringBuilder(); 55 sb.append("["); 56 while (curr != null) { 57 sb.append(curr.toString()).append(","); 58 curr = curr.next; 59 } 60 sb.deleteCharAt(sb.length() - 1); 61 sb.append("]"); 62 return sb.toString(); 63 } 64 65 public void display() { 66 System.out.println(toString()); 67 } 68 } 69 /** 70 * 队列类 71 * 和上个例子的栈类的实现一样,都是强调概念上的实体,独立于它们的具体实现。 72 * 用数组或是链表实现栈和队列都是一样的。栈的重要性是它的push pop操作,以及如何使用它们;队列的重要性是从队头移除,从队尾插入,以及如何使用。 73 * 实现这些操作的内在机制从其重要性上讲,其实是不重要的。 74 */ 75 class LinkQueue{ 76 private FirstLastLink link; 77 public LinkQueue(){ 78 link = new FirstLastLink(); 79 } 80 public boolean isEmpty(){ 81 return this.link.isEmpty(); 82 } 83 public void insert(LinkQ l){ 84 this.link.insertLast(l); 85 } 86 public LinkQ remove(){ 87 return this.link.deleteFirst(); 88 } 89 public String toString(){ 90 return this.link.toString(); 91 } 92 public void display(){ 93 System.out.println(toString()); 94 } 95 } 96 public class LinkQueueDemo { 97 public static void main(String[] args) { 98 LinkQueue queue = new LinkQueue(); 99 for (int i = 0; i < 5; i++) { 100 LinkQ l= new LinkQ(i); 101 queue.insert(l); 102 queue.display(); 103 } 104 while(!queue.isEmpty()){ 105 System.out.print("移除元素:"+queue.remove()); 106 System.out.print(".现在队列为: "); 107 queue.display(); 108 } 109 } 110 }