数据结构之用java实现队列(以及实现迭代器方法)

  • Post author:
  • Post category:java


package Queue;

import java.util.Iterator;

public class Queue<T> implements Iterable<T> {
    private Node first;

    private Node last;

    private int N;

    private class Node {
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }

    }

    public Queue() {
        this.first = new Node(null, null);
        this.last = null;
        N = 0;
    }

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

    public int size() {
        return N;
    }

    public void inQueue(T t) {
        if (last == null) {
            last = new Node(t, null);
            first.next = last;
        } else {
            Node oldlast = last;
            last = new Node(t, null);
            oldlast.next = last;
        }
        N++;
    }

    public T outQueue() {
        if (isEmpty()) {
            return null;
        }
        Node firstNode = first.next;
        first.next = firstNode.next;
        N--;
        if (isEmpty()) {
            last = null;
        }
        return firstNode.item;

    }

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

    public class Qiterator implements Iterator {
        private  Node n;

        public Qiterator() {
            this.n = first;
        }

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

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}

测试类

package Queue;


public class TestQueue {
    public static void main(String[] args) {
        Queue<String> queue = new Queue<String>();
        queue.inQueue("1");
        queue.inQueue("2");
        queue.inQueue("3");
        queue.inQueue("4");
        for (String s : queue) {
            System.out.println(s);
        }
        System.out.println("---------------------------");
        int a=queue.size();
        for (int i = 0; i <a ; i++) {
            System.out.println(queue.outQueue());
        }

    }
}

注意循环时不能这么写(因为我们每次遍历这个值都会变queue.size())

for (int i = 0; i <queue.size() ; i++) {
            System.out.println(queue.outQueue());
        }



版权声明:本文为weixin_44893467原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。