编程语言
首页 > 编程语言> > 5、链表队列(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

 

标签:Node,printQueue,java,temp,队列,linkQueue,next,链表,public
来源: https://www.cnblogs.com/karrya/p/11031574.html