java實現鏈式隊列。。。比較簡單
package datastruct; public class QueueLink implements Queue { // 定義一個節點內部類 class Node { private Object data; private Node next; public Node(Object obj) { this.data = obj; } public Node() { } } // 定義鏈式隊列的一些屬性 private Node head; // 頭指針(引用) private Node rear; // 尾指針(引用) private int length; // 隊列的長度,開始為1 private Node temp; // 臨時指針(引用) // 初始化隊列,空頭指針 public QueueLink() { head = new Node(); rear = head; length = 1; } // 初始化隊列,有數據頭指針 public QueueLink(Object obj) { head = new Node(obj); rear = head; length = 1; } public boolean clear() { // TODO Auto-generated method stub if(this.length==1){ return true; }else if(length==2){ head.next=null; //沒有引用的節點java會自動回收內存 }else { while(head.next.next!=null){ head.next=head.next.next; } head.next=null; return true; } return false; } // 判空 public boolean isEmpty() { // TODO Auto-generated method stub if (this.length() == 1) { return true; } else { return false; } } // 獲得隊列的長度 public int length() { // TODO Auto-generated method stub return this.length; } // 添加一個節點 public void offer(Object x) { this.temp = new Node(x); // 隊列使用尾插法 rear.next = temp; rear = temp; this.length++; // TODO Auto-generated method stub } // 查看第一個節點 public Node peek() { // TODO Auto-generated method stub if (length == 1) { temp=null; } else { temp= head.next; } return temp; } //刪除第一個節點 public Node poll() { // TODO Auto-generated method stub if(length==1){ //無法刪除 temp=null; }else if(length==2){ this.temp= head.next; //置空下一個節點就可以了 head.next=null; length--; }else{ this.temp= head.next; this.head.next=this.head.next.next; length--; } return temp; } //test public static void main(String[] args) { QueueLink linkQueue = new QueueLink(); System.out.println("隊列是否為空:"+linkQueue.isEmpty()); System.out.println("連續入隊-------------------------------"); for(int i=0;i<5;i++){ linkQueue.offer((char)(97+i)); } System.out.println("隊列長度為:"+linkQueue.length()); System.out.println("隊首元素為:"+linkQueue.peek().data); //出隊 System.out.println("連續出隊-------------------------------"); for(int i=0;i<4;i++){ Object data=linkQueue.poll(); } System.out.println("隊列長度為:"+linkQueue.length()); } }
結果為:
隊列是否為空:true 連續入隊------------------------------- 隊列長度為:6 隊首元素為:a 連續出隊------------------------------- 隊列長度為:2