zoukankan      html  css  js  c++  java
  • 5、链表队列(java实现)

    1、图例

    2、链表节点

    public class Node<T> {
        public T data;
        public Node next;
    }

    3、具体实现

    public class LinkQueue<T> {
        private static Node head;
        private static Node tail;
        private static int size;
    
        /**
         * 初始化
         */
        public void initQueue() {
            Node node = new Node();
            node.data = null;
            node.next = null;
            head = tail = node;
            size = 0;
        }
    
        /**
         * 是否空
         *
         * @return
         */
        public static boolean isEmpty() {
            return head == tail;
        }
    
        /**
         * 入队列
         *
         * @param element
         */
        public void insertQueue(T element) {
            Node temp = new Node();
            temp.data = element;
    
            tail.next = temp;   //放节点
            tail = temp;        //移动尾指针
            size++;
        }
    
        /**
         *
         */
        public void popQueue() {
            if (isEmpty()) {
                System.out.println("队列已空,!!!");
                return;
            }
            Node temp = head.next;         //创建节点指向头结点所指向
            System.out.println("出队列: "+temp.data);
            head.next = temp.next;
            if (tail == temp) {
                tail = head;
            }
            size--;
        }
    
        /**
         * 元素个数
         */
        public static void sizeQueue() {
            System.out.println("元素个数:"+size);
        }
    
        /**
         * 遍历元素
         */
        public static void printQueue() {
            for (Node current = head.next;current != null;current = current.next){
                System.out.print(current.data+" ");
            }
            System.out.println();
        }
        public static void main(String[] args) {
            LinkQueue linkQueue = new LinkQueue();
            linkQueue.initQueue();
    
            linkQueue.insertQueue(1);
            printQueue();
            linkQueue.insertQueue(2);
            printQueue();
            linkQueue.insertQueue(3);
            printQueue();
            linkQueue.insertQueue(4);
            printQueue();
    
            linkQueue.popQueue();
            printQueue();
            linkQueue.popQueue();
            printQueue();
            linkQueue.insertQueue(5);
            printQueue();
    
            sizeQueue();
    
        }

    4、实现结果

    1 
    1 2 
    1 2 3 
    1 2 3 4 
    出队列: 1
    2 3 4 
    出队列: 2
    3 4 
    3 4 5 
    元素个数:3
  • 相关阅读:
    洛谷P3819 松江1843路
    洛谷P1896 [SCOI2005]互不侵犯King
    洛谷P1197 [JSOI2008]星球大战
    洛谷P1171 售货员的难题
    2017-10-24 NOIP模拟赛
    LibreOJ #6192. 「美团 CodeM 复赛」城市网络
    洛谷P2258 子矩阵
    Cogs 9. 中心台站建设
    Cogs 6. 线型网络
    洛谷P3138 [USACO16FEB]负载平衡Load Balancing_Silver
  • 原文地址:https://www.cnblogs.com/karrya/p/11031574.html
Copyright © 2011-2022 走看看