java用链表实现队列

3 篇文章 0 订阅
1 篇文章 0 订阅

一. 基本概念

队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

二. 实现

//节点类
public class Node {
    public Object data;
    public Node next;

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

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

/**
 * 队列:队尾插入,队头删除
 */
public class MyQueue<E> {
    //队头
    private Node front;
    //队尾
    private Node rear;

    /**
     * 入队
     * @param element
     */
    public void enQueue(E element){
        Node node = new Node(element);
        if (null == front && null == rear){
            front = node;
            rear = node;
        }else {
            rear.next = node;
            rear = node;
        }
    }

    /**
     * 出队
     * @return
     */
    public E deQueue(){
        if (null == front && null == rear) throw new RuntimeException("队列为空");
        Node node = front;
        Object obj = node.data;
        front = front.next;
        if (rear == node)
            rear = rear.next;
        return (E) obj;
    }

    /**
     * 打印队列元素
     * @return
     */
    @Override
    public String toString() {
        if (null == front && null == rear) return "[]";
        StringBuilder sb = new StringBuilder("[");
        Node temp = front;
        sb.append(temp.data+",");
        while (temp != rear){
            temp = temp.next;
            sb.append(temp.data+",");
        }
        sb.setCharAt(sb.length()-1 , ']');
        return sb.toString();
    }
}

//测试类
public class TestMyQueue {
    public static void main(String[] args) {
        MyQueue<String> myQueue = new MyQueue<>();
        //System.out.println("出队元素为: "+myQueue.deQueue());
        myQueue.enQueue("a");
        System.out.println("队列内元素为: "+ myQueue.toString());
        System.out.println("出队元素为: "+myQueue.deQueue());
        System.out.println("队列内元素为: "+ myQueue.toString());
        myQueue.enQueue("a");
        myQueue.enQueue("b");
        myQueue.enQueue("c");
        System.out.println("队列内元素为: "+ myQueue.toString());
        System.out.println("出队元素为: "+myQueue.deQueue());
        System.out.println("队列内元素为: "+ myQueue.toString());
    }
}

测试结果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值