Search code examples
doubly-linked-list

How to insert an Element in a doubly linked list without repetion?


I am trying to write a code that inserts an Element in a doubly linked list without repetition but it's not working.

Any help would be appreciated. This is my code:

public void insert(int value) {
        Element tmp = new Element(value);
        
        if(this.head == null) {
            this.head = this.rear = tmp;
            return ;
        }
        
        if(this.head.data < value) {
            tmp.next = this.head;
            this.head.previous = tmp;
            tmp.previous = null;
            this.head = tmp;
            return ;
        }
        
        if(this.rear.data > value) {
            tmp.previous = this.rear;
            this.rear.next = tmp;
            this.rear = tmp;
            return ;
        }
        else {
        Element cur = this.head;
        while(cur.next != null && cur.next.data > value)            
            cur = cur.next;
        
        tmp.next = cur.next;
        tmp.previous = cur;
        cur.next.previous = tmp;
        cur.next = tmp;
        }
        return ;
    }

Solution

  • You should add a second method:

    public boolean isInList(int value) {
            Element cur = this.head;
            
            if(this.head == null)
                return false;
            
            while(cur != null) {
                if(cur.data == value)
                    return true;
                cur = cur.next;
            }
            return false;
        }
    

    And then add it to the insert method:

    public void insert(int value) {
            Element tmp = new Element(value);
            
            if(this.isInList(value))
                return false;
            
            if(this.head == null) {
                this.head = this.rear = tmp;
                return ;
            }
            
            if(this.head.data < value) {
                tmp.next = this.head;
                this.head.previous = tmp;
                tmp.previous = null;
                this.head = tmp;
                return ;
            }
            
            if(this.rear.data > value) {
                tmp.previous = this.rear;
                this.rear.next = tmp;
                this.rear = tmp;
                return ;
            }
            else {
            Element cur = this.head;
            while(cur.next != null && cur.next.data > value)            
                cur = cur.next;
            
            tmp.next = cur.next;
            tmp.previous = cur;
            cur.next.previous = tmp;
            cur.next = tmp;
            }
            return ;
        }