如何在双向链表中不重复地插入一个元素?

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

我正在尝试编写一个代码,在双向链表中不重复地插入一个元素,但它不起作用。

如有任何帮助,我们将不胜感激。 这是我的代码:

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 ;
    }

您应该添加第二种方法:

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;
    }

然后添加到insert方法中:

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 ;
    }