Java用链表实现队列

/**
 * 链表实现队列
 */
public class LinkedQueue {
    class Node{
        int val;
        Node next;
        public Node(int val){this.val=val;}
        public Node(int val,Node next){this.val=val;this.next=next;}
    }

    // 队头指针
    Node front;
    // 队尾指针
    Node rear;
    // 队列长度
    int queueSize;
    public LinkedQueue(){}

    /**
     * 入队,如果队列为空,则将头尾指针都指向这个元素,否则将队尾元素的next域设为新入队元素,再将尾指针指向新入队元素
     * @param element
     * @return
     */
    public boolean enQueue(int element){
        if(isEmpty()){
            front=new Node(element,null);
            rear=front;
            queueSize++;
            return true;
        }
        Node node = new Node(element,null);
        rear.next=node;
        rear=node;
        queueSize++;
        return true;
    }

    /**
     * 出队,头指针指向它的next域,如果队列中只有一个元素,那么将尾指针也只想next域,也就是null
     * @return
     */
    public int deQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列已经空了!");
        }
        int element=front.val;
        front=front.next;
        if(queueSize==1){
            rear=front;
        }
        queueSize--;
        return element;
    }

    public boolean isEmpty(){
        return front==null && front==rear && queueSize==0;
    }

}

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值