如题:
顺序队列,数组实现:
public class Array_Queue { int[] a=new int[5]; int front=0,rear=0,count=0; public boolean isEmpty() { if(front==rear&&count==0) { return true; } else { return false; } } public boolean isFull() { if(front==rear&&count>0) { return true; } else { return false; } } public void enQueue(int x) { if(!isFull()) { a[rear]=x; rear=(rear+1)%(a.length); count++; } else { System.out.println("Array_Queue is Full!"); } } public int deQueue() { int t; if(!isEmpty()) { t=a[front]; front=(front+1)%(a.length); count--; } else { System.out.println("Array_Queue is Empty!"); t=-1; } return t; } }
主程序c1:
//顺序队 Array_Queue myaq=new Array_Queue(); int t; for (int i = 1; i <= 6; i++) { myaq.enQueue(i); } // //debug1 // for (int item : myaq.a) // { // System.out.print("debug1"+item+" "); // } // System.out.println("front:"+myaq.front+"rear:"+myaq.rear+"count:"+myaq.count); // //debug1 for (int i = 1; i <= 2; i++) { t = myaq.deQueue(); if (t != -1) { System.out.print(t + " "); } } for (int i = 7; i <= 8; i++) { myaq.enQueue(i); } for (int i = 1; i <= 10; i++) { t = myaq.deQueue(); if (t != -1) { System.out.print(t + " "); } }
运行结果:
Array_Queue is Full! 1 2 3 4 5 7 8 Array_Queue is Empty! Array_Queue is Empty! Array_Queue is Empty! Array_Queue is Empty! Array_Queue is Empty!
链式队列节点代码:
链式队列代码:
public class Linked_Queue { Linked_Node front,rear; public Linked_Queue() { front=new Linked_Node(); rear=front; } public boolean isEmpty() { if (front.next==null) { return true; } else { return false; } } public void enQueue(int x) { rear.next =new Linked_Node(x); rear.next.pre=rear; rear = rear.next; } public int deQueue() { int t; if (!isEmpty()) { t = front.next.v; front.next = front.next.next; if(front.next!=null) { front.next.pre=front; } else { rear=front; } } else { System.out.println("Array_Queue is Empty!"); t = -1; } return t; } }
主程序:
运行结果:
链表头结点全都有“头”(即木头乌龟)。根据自己的理解和喜好,程序是活的。