Best implementation of Java Queue?

后端 未结 9 708
有刺的猬
有刺的猬 2020-12-23 16:23

I am working (in Java) on a recursive image processing algorithm that recursively traverses the pixels of the image, outwards from a center point.

Unfortunately, tha

9条回答
  •  温柔的废话
    2020-12-23 16:37

    O(1) access to first and last nodes.

    class Queue {
    
        private Node head;
        private Node end;
    
        public void enqueue(Integer data){
    
            Node node = new Node(data);
            if(this.end == null){
                this.head = node;
                this.end = this.head;
            }
            else {
                this.end.setNext(node);
                this.end = node;
            }
        }
    
        public void dequeue (){
    
            if (head == end){
                end = null;
            }
    
            head = this.head.getNext();
        }
    
    
        @Override
        public String toString() {
            return head.getData().toString();
        }
    
        public String deepToString() {
    
            StringBuilder res = new StringBuilder();
            res.append(head.getData());
    
            Node cur = head;
            while (null != (cur = cur.getNext())){
                res.append(" ");
                res.append(cur.getData());
    
            }
            return res.toString();
        }
    }
    
    class Node {
    
        private Node next;
        private Integer data;
    
    
        Node(Integer i){
            data = i;
        }
    
        public Integer getData() {
            return data;
        }
    
        public Node getNext() {
            return next;
        }
    
        public void setNext(Node next) {
            this.next = next;
        }
    }
    

提交回复
热议问题