Doubly Linked List - appointing a tail

Hello I have a doubly linked list without implementing, my issue is that I'm not sure how can I apoint a tail because of the constructor for Element that feels confusing to me, it is my homework so it has to be done with that constructor . So far, my method addFirst does its job but it doesn't have a tail

I can not use getters and setters

Thank you

public class Element {
    private int value;
    private Element next;
    private Element previous;

    public Element(int value, Element next, Element previous) {
        this.value = value;
        this.next = next;
        this.previous = previous;
    }
}

public class Liste {

    private Element first;
    private Element last;

    void addFirst(int value) {
        if(this.first!=null) {
            this.first= new Element(value,this.first,null);
        }
        else {
            this.first= new Element(value,null,null);
        }

    }

2 answers

  • answered 2018-03-13 21:27 bcr666

    You just need to check if the last is null. That way, the first time you put something in the list, it is the first and last. You also don't need to check to see if first is null when instantiating the new Element, the system will put null in for you.

    public class Element {
        private int value = 0;
        private Element next = null;
        private Element previous = null;
    
        public Element(int value, Element next, Element previous) {
            this.value = value;
            this.next = next;
            this.previous = previous;
        }
    
        public Element insertBefore(int value) {
            Element that = new Element(value, this, null);
            previous = that;
            return that;
        }
    } 
    
    public class Liste {
        private Element first;
        private Element last;
    
        void addFirst(int value) {
            if (first == null) {
                Element newElement = new Element(value, null, null);
                first = newElement;
                last = newElement;
            } else {
                first = first.insertBefore(value);
            }
        }
    }
    

  • answered 2018-03-13 21:28 RAZ_Muh_Taz

    Here is a simple addElement method where we first check for an empty list else we traverse the list until we reach the end. Once we reach the end, we add the new Element to the list and set it's previous to the previous last Element. Finally we set the last variable to the new Element we just added to the list.

    void addElement(int val)
    {
        if(first == null)
        {
            first = new Element(val, null, null);
            last = first;
        }
        else
        {
            Element ref = first;
            while(ref.next != null)
                ref = ref.next;
    
            ref.next = new Element(val, ref, null); //added to the end of the list
            last = ref.next; //set the last Element to the one we just created
        }
    }