Skip to main content
 首页 » 编程设计

java算法之自定义线性结构-队列

2022年07月18日130jirigala
/** 
 * @desc: 队列--单链表实现 
 * @author: 毛会懂 
 * @create: 2020-12-30 10:55:00 
 **/ 
public class MyQueue<T> implements Iterable<T>{ 
    private Node head; 
    private Node last; //尾节点 
    private Integer count; 
 
    MyQueue(){ 
        head = new Node(null,null); 
        last = null; 
        count = 0; 
    } 
 
    //进队列 
    public void enter(T t){ 
        Node newNode = new Node(t,null); 
        if(isEmpty()){ 
            head.next = newNode; 
        }else { 
            last.next = newNode; 
        } 
        last = newNode; 
        count++; 
    } 
 
    //出队列 
    public T del(){ 
        if(isEmpty()){ 
            return null; 
        } 
        Node node = head.next; 
        head.next = node.next; 
        count--; 
        //只有一个元素出队列 
        if(isEmpty()){ 
            last = null; 
        } 
        return node.t; 
    } 
 
 
    //队列是否为空 
    public Boolean isEmpty(){ 
        return count == 0; 
    } 
 
    //队列的大小 
    public Integer size(){ 
        return count; 
    } 
 
    @Override 
    public Iterator<T> iterator() { 
        return new MyIterator(); 
    } 
 
    private class MyIterator implements Iterator{ 
        private Node node; 
 
        public MyIterator(){ 
            node = head; 
        } 
 
        @Override 
        public boolean hasNext() { 
            return node.next != null; 
        } 
 
        @Override 
        public T next() { 
            node = node.next; 
 
            return node.t; 
        } 
    } 
 
 
    private class Node{ 
        private T t; 
        private Node next; 
 
        public Node(T t, Node next) { 
            this.t = t; 
            this.next = next; 
        } 
    } 
}

测试:

public static void main(String[] args) {
MyQueue<String> myQueue = new MyQueue<>();
myQueue.enter("abc");
myQueue.enter("bddd");
for (String s : myQueue) {
System.out.println(s);
}
System.out.println("--------");
System.out.println("是否为空:" + myQueue.isEmpty());
System.out.println("队列大小:" + myQueue.size());
System.out.println(myQueue.del());
System.out.println(myQueue.del());
System.out.println("------");
myQueue.enter("sss");
myQueue.enter("bb");
myQueue.enter("cc");
myQueue.forEach(System.out::println);
System.out.println(myQueue.del());
}

本文参考链接:https://www.cnblogs.com/maohuidong/p/14216144.html
阅读延展