我想删除链表中的重复项,我想在列表中保留唯一项,知道如何做吗?
注意:此作业中禁止使用哈希表

该项目中使用的所有数据结构必须由学生实施。
严格禁止使用Java集合或任何其他库。

class Node<T> {
public T data;
public Node<T> next;

public Node (T val) {
    data = val;
    next = null;
}}


以下是LinkeList类

public class LinkedList<T> {
private Node<T> head;
private Node<T> current;

public LinkedList () {
    head = current = null;
}

public boolean empty () {
    return head == null;
}

public boolean last () {
    return current.next == null;
}

public boolean full () {
    return false;
}

public void findFirst () {
    current = head;
}
public void findNext () {
    current = current.next;
}

public T retrieve () {
    return current.data;
}

public void update (T val) {
    current.data = val;
}

public void insert (T val) {
    Node<T> tmp;
    if (empty()) {
        current = head = new Node<T> (val);
    }
    else {
        tmp = current.next;
        current.next = new Node<T> (val);
        current = current.next;
        current.next = tmp;
    }
}

public void remove () {
    if (current == head) {
        head = head.next;
    }
    else {
        Node<T> tmp = head;
        while (tmp.next != current)
            tmp = tmp.next;
        tmp.next = current.next;
    }
    if (current.next == null)
        current = head;
    else
        current = current.next;
}}


LinkedList元素

    public static void main(String[] args) {

    LinkedList<Integer> list=new LinkedList<>();

    list.insert(1);
    list.insert(2);
    list.insert(1);
    list.insert(3);
    list.insert(1);
    list.insert(2);
    list.insert(4);
    list.insert(3);
    list.insert(5);
    list.insert(4);
    list.insert(7);
    list.insert(1);
    list.insert(6);
    list.insert(5);
    list.insert(6);
    list.insert(1);
    list.insert(2);}


我一直坚持下去,请帮忙

谢谢

最佳答案

尝试添加contain()方法(请注意,此代码是受LinkedList代码源的启发,您可以LinkedList.contains(Object o)进行检查)

public boolean contain(T o) {
    if (o == null) { // assuming that your list accept to add null object
        for (Node<T> x = first; x != null; x = x.next) {
            if (x.data == null)
                return true;
        }
    } else {
        for (Node<T> x = first; x != null; x = x.next) {
            if (o.equals(x.data))
                return true;
        }
    }
    return false;
}


并编辑您的insert()方法,以在添加对象之前检查该对象是否已存在

public void insert (T val) {
    Node<T> tmp;
    if (empty()) {
        current = head = new Node<T> (val);
    }
    else if(!contain(val)) { // the object val will be added only if it not exist in the list
        tmp = current.next;
        current.next = new Node<T> (val);
        current = current.next;
        current.next = tmp;
    }
}

关于java - 删除LinkedList重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40546163/

10-12 22:30