posts - 22, comments - 32, trackbacks - 0, articles - 73
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          JAVA 實現鏈表隊列

          Posted on 2017-03-28 15:48 為自己代言 閱讀(392) 評論(0)  編輯  收藏 所屬分類: 算法/數據結構
          package stacktest;

          /**
          * @Author: zzz
          * @CreateTime: 2017/3/28 10:52
          * @Description: 隊列特點(先進先出),鏈表實現的隊列 在隊頭刪除元素,在隊尾插入元素。
          * 這樣才能滿足隊列的特性。
          */
          public class MyQueue<T> {
          private Node<T> front; //隊列頭,只能刪除元素

              private Node<T> rear; //隊列尾,只能用來插入入元素

              private int size;//隊列的長度

          /**
          * 初始化隊列
          */
          public MyQueue() {
          front = new Node<T>();
          rear = front;
          }

          /**
          * 鏈表的數據結構
          */
          private class Node<T> {
          public T data;
          public Node<T> next;

          public Node(T data, Node next) {
          this.data = data;
          this.next = next;
          }

          public Node(T data) {
          this.data = data;
          }

          public Node() {
          }
          }

          public void add(T data) {
          //新插入的節點永遠是尾節點,它的next 指向null(即沒有后繼節點)
                  Node newNode = new Node(data, null);
          //讓尾節點next指向新節點
                  rear.next = newNode;
          rear = newNode;
          size++;
          }

          public T pop() throws Exception {
          if (size < 1) {
          throw new Exception("錯誤,隊列為空。");
          }
          Node<T> nextNode = front.next;

          front.next = nextNode.next;
          size--;
          if (size < 1) {
          rear = front;
          size = 0;
          }
          return nextNode.data;

          }

          //取隊首元素

          public T peek() throws Exception {
          if (size < 1){
          throw new Exception("錯誤,隊列為空。");
          };
          return front.next.data;

          }
          //返回隊列的大小
          public int getSize() {
          return size;
          }

          //判斷隊列是否為空
          public boolean isEmpty() {
          return size == 0;
          }

          /**
          * 遍歷算法,移動front指針,直到front指針追上rear指針
          */
          public void traverse(){
          for(Node currentNode=front.next; currentNode!=null; currentNode=currentNode.next ){
          System.out.println(currentNode.data);
          }
          }

          public static void main(String[] args)throws Exception{
          MyQueue<String> queue=new MyQueue<>();
          for(int i=0;i<10;i++){
          queue.add("88888-"+i);
          }

          /* for(int i=0;i<10;i++){
          String s=queue.pop();
          System.out.print(s+";");
          }*/
          queue.traverse();

          }
          }
          主站蜘蛛池模板: 临武县| 老河口市| 乌恰县| 汪清县| 博野县| 荣昌县| 儋州市| 南华县| 太谷县| 鹤峰县| 潞西市| 镇宁| 密云县| 绩溪县| 孝感市| 江油市| 大足县| 梁山县| 敦化市| 出国| 定日县| 卫辉市| 丰台区| 建水县| 福建省| 乌什县| 民县| 延安市| 盐城市| 东源县| 武川县| 广汉市| 高台县| 张家口市| 齐河县| 苍梧县| 永平县| 榆中县| 温泉县| 吐鲁番市| 彰化县|