在上一篇博文中通過java實現了隊列的連續存儲,下面來討論隊列的鏈式存儲,即鏈隊列。
鏈隊列的定義:
隊列的鏈式存儲結構簡稱爲鏈隊列。它是限制僅在表頭刪除和表尾插入的單鏈表。
鏈隊列的數據存儲形式:
鏈隊列基本運算的實現:
- package study_02.datastructure.queue;
- /**
- * 鏈隊列
- * @author WWX
- */
- public class LinkQueue<T> {
- //鏈的數據結構
- private class Node{
- public T data;
- public Node next;
- //無參構造函數
- public Node(){}
- public Node(T data,Node next){
- this.data=data;
- this.next=next;
- }
- }
- //隊列頭指針
- private Node front;
- //隊列尾指針
- private Node rear;
- //隊列長度
- private int size=0;
- public LinkQueue(){
- Node n=new Node(null,null);
- n.next=null;
- front=rear=n;
- }
- /**
- * 隊列入隊算法
- * @param data
- * @author WWX
- */
- public void enqueue(T data){
- //創建一個節點
- Node s=new Node(data,null);
- //將隊尾指針指向新加入的節點,將s節點插入隊尾
- rear.next=s;
- rear=s;
- size++;
- }
- /**
- * 隊列出隊算法
- * @return
- * @author WWX
- */
- public T dequeue(){
- if(rear==front){
- try {
- throw new Exception("堆棧爲空");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }else{
- //暫存隊頭元素
- Node p=front.next;
- T x=p.data;
- //將隊頭元素所在節點摘鏈
- front.next=p.next;
- //判斷出隊列長度是否爲1
- if(p.next==null)
- rear=front;
- //刪除節點
- p=null;
- size--;
- return x;
- }
- }
- /**
- * 隊列長隊
- * @return
- * @author WWX
- */
- public int size(){
- return size;
- }
- /**
- * 判斷隊列是否爲空
- * @return
- * @author WWX
- */
- public boolean isEmpty(){
- return size==0;
- }
- public String toString() {
- if(isEmpty()){
- return "[]";
- }else{
- StringBuilder sb = new StringBuilder("[");
- for(Node current=front.next;current!=null;current=current.next){
- sb.append(current.data.toString() + ", ");
- }
- int len = sb.length();
- return sb.delete(len - 2, len).append("]").toString();
- }
- }
- //測試
- public static void main(String[] args) {
- LinkQueue<Integer> queue=new LinkQueue<Integer>();
- queue.enqueue(1);
- queue.enqueue(2);
- queue.enqueue(3);
- queue.enqueue(4);
- queue.enqueue(5);
- queue.enqueue(6);
- System.out.println(queue);
- System.out.println("出隊:"+queue.dequeue());
- System.out.println("隊列長度="+queue.size());
- System.out.println(queue);
- System.out.println("出隊:"+queue.dequeue());
- System.out.println("隊列長度="+queue.size());
- System.out.println(queue);
- System.out.println("出隊:"+queue.dequeue());
- System.out.println("隊列長度="+queue.size());
- System.out.println(queue);
- }
- }
輸出結果:
[1, 2, 3, 4, 5, 6]
出隊:1
隊列長度=5
[2, 3, 4, 5, 6]
出隊:2
隊列長度=4
[3, 4, 5, 6]
出隊:3
隊列長度=3
[4, 5, 6]
原文地址:http://blog.csdn.net/sky_zhangfan/article/details/3959847