java数据结构--队列

java数据结构–队列

在这里插入图片描述

队列类

import java.util.Iterator;

public class MyQueue<T> implements Iterable<T> {

    private class Node<T> {
        private T data;
        private Node<T> next;

        public Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    private Node head;
    private Node last;
    private int length;

    public MyQueue() {
        head = new Node(null, null);
        last = null;
        length = 0;
    }

    public boolean isEmpty() {
        return length == 0;
    }

    public int size() {
        return length;
    }

    public void enqueue(T t) {
        if (last == null) {
            last = new Node(t, null);
            head.next = last;
        } else {
            Node<T> oldlast = last;
            last = new Node(t, null);
            oldlast.next = last;
        }
        length++;
    }

    public T dequeue() {
        Node<T> oldNode = null;
        if (isEmpty()) {
            throw new MyException("空队列");
        }
        /*
        自己写的,代码臃肿
        else{
            if(head.next==last){
                oldNode=last;
                last=null;
                head.next=null;
            }else{
                oldNode=head.next;
                head.next=head.next.next;
            }*/

        oldNode = head.next;
        head.next = oldNode.next;
        length--;
        if (isEmpty()) {
            last = null;
        }
        return oldNode.data;
    }

    @Override
    public Iterator<T> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator {
        Node<T> tempNode = null;

        public Itr() {
            tempNode = head;
        }

        @Override
        public boolean hasNext() {
            return tempNode.next != null;
        }

        @Override
        public Object next() {
            tempNode = tempNode.next;
            return tempNode.data;
        }
    }
}

class MyException extends RuntimeException {
    private String message;

    public MyException(String message) {
        super(message);
        this.message = message;
    }
}

测试类

public class MyQueueTest {
    public static void main(String[] args) {
        MyQueue<String> myQueue=new MyQueue<>();
        myQueue.enqueue("小明");
        myQueue.enqueue("小红");
        myQueue.enqueue("小黄");
        for(String str:myQueue){
            System.out.println(str);
        }
        System.out.println(myQueue.dequeue());
        System.out.println(myQueue.dequeue());
        System.out.println(myQueue.dequeue());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值