How to do a cyclic doubly link list add method in java

后端 未结 3 573
孤城傲影
孤城傲影 2021-01-28 16:24

I am implementing the add(E) method in the cyclic DoublyLinkedList class as well as the Node inner class.

Node should be implemented as a private inner class.

D

3条回答
  •  悲&欢浪女
    2021-01-28 17:17

    EDIT:

    One mistake is here: Instead of this line this.next = prev; it should have this.prev = prev;

    However, if you fix this line the code will still not work. This is a simplified version of your code that works.

    public class DoublyLinkedList {
    
        private static class Node {
    
            private final E data;
            private Node next;
            private Node prev;
    
            Node(E data) {
                this.data = data;
                this.next = this;
                this.prev = this;
            }
    
            Node(E data, Node next) {
                this.data = data;
                this.next = next;
                next.prev = this;
            }
        }
    
        private Node head;
        private Node tail;
        private int size;
    
        public void add(E value) {
            if (this.head == null) {
                this.head = new Node<>(value);
                this.tail = head;
            } else {
                this.head = new Node<>(value, head);
                this.head.prev = this.tail;
                this.tail.next = head;
            }
            size++;
        }
    
        public void forEach(Consumer consumer) {
            Node node = this.head;
    
            if (node != null) {
                do {
                    consumer.accept(node.data);
                    node = node.next;
                } while (node != this.head);
            }
        }
    
        public static void main(String[] args) {
            DoublyLinkedList list = new DoublyLinkedList<>();
    
            list.add(1);
            list.add(2);
            list.add(3);
    
            list.forEach(e -> System.out.print(e + ", "));
        }
    
    }
    

    What I've done: in order to create a circular double linked list I keep a reference to the tail.

提交回复
热议问题