链表队列

import java.util.Iterator;

/**
 * 链表是实现队列 FIFO
 * 成员变量:队头引用 first、队尾引用 last、大小 count、节点内部类 Node
 * 私有方法:
 * 公开方法:入队列 enqueue、出队列 enqueue、大小 size、是否为空 isEmpty、
 * 要求:实现泛型、迭代器
 */
public class LinkedQueue<Item> implements Iterable<Item> {
    private Node first;
    private Node last;
    private int count;

    public LinkedQueue() {
        this.first = null;
        this.last = null;
        this.count = 0;
    }

    private class Node{
        Item item;
        Node next;

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

    public void enqueue(Item e){
        Node temp = new Node(e,null);
        if(count==0){
            first = temp;
            last = temp;
        }
        last.next = temp;
        last = temp;
        count++;
    }

    public Item dequeue(){
        if(count==0)return null;
        Item temp = first.item;
        first=first.next;
        count--;
        return temp;
    }

    public int size(){
        return count;
    }

    public boolean isEmpty(){
        if(count==0)return true;
        return false;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iterator<Item>() {
            Node i = first;
            @Override
            public boolean hasNext() {
                if(i!=null) return true;
                return false;
            }

            @Override
            public Item next() {
                Item temp = i.item;
                i=i.next;
                return temp;
            }
        };
    }
}

 

 

/**
 * 测试案例
 */
public class TestCase {
    public static void main(String[] args) {
        LinkedQueue<Integer> integers = new LinkedQueue<>();
        integers.enqueue(1);
        integers.enqueue(2);
        integers.enqueue(3);
        integers.enqueue(4);
        integers.enqueue(5);
        System.out.println(integers.dequeue());
        System.out.println(integers.isEmpty());
        System.out.println(integers.size());
        System.out.println("===================");
        for(Integer e : integers){
            System.out.println(e);
        }
    }
}


//结果
1
false
4
===================
2
3
4
5

 

上一篇:Function and Function


下一篇:【LeetCode】11.Array and String —Array Partition I 数组分区