MyQueue(队列)

目录

 一、队列的定义

二、队列方法的实现

1、定义队列

2、后端插入

3、前端操作

4、判断队列是否为空

5、队列大小

三、队列方法的使用


 一、队列的定义

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

  用双向链表实现一个队列

二、队列方法的实现

1、定义队列

public class MyQueue{


    static class ListNode {


        public int val;


        public ListNode next;


        public ListNode prev;


        public ListNode(int val) {

            this.val = val;

        }


    }

        public ListNode head;


        public ListNode last;


        public int UsedSize;




2、后端插入

 public boolean offer(int val) {

        ListNode node = new ListNode(val);

        if (head == null) {

            head = node;

            last = node;


        } else {

            last.next = node;

            node.prev = last;

            last = node;


        }

        UsedSize++;

        return true;

    }

3、前端操作

取出头节点的值并将头节点从链表中取出:

public int pop() {

        if (head == null) {

            return -1;

        }

        int retVal = head.val;

        if (head.next == null) {

            return retVal;

        }

        head = head.next;
、
        head.prev = null;

        UsedSize--;

        return retVal;

    }

取出头节点的值但不将头节点从链表中取出:

public int peek(){


        if (head==null){

            return -1;

        }

        return head.val;

    }

4、判断队列是否为空

 public boolean empty(){

        return head==null;

    }

5、队列大小

public int size(){

       return UsedSize;

    }

三、队列方法的使用

定义一个Main类,对定义的方法进行使用。

public class Main {

    public static void main(String[] args) {


       MyQueue myQueue=new MyQueue();


       myQueue.offer(1);

       myQueue.offer(2);

       myQueue.offer(3);

       myQueue.offer(4);

       myQueue.offer(5);

       myQueue.offer(6);


        System.out.println(myQueue.pop());


        System.out.println(myQueue.peek());


        System.out.println(myQueue.empty());


        System.out.println(myQueue.size());

        
    }

}

执行结果:

1
2
false
5


以上就是对队列的简单实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值