要提高Java链表类的查找效率,可以采用以下方法:
import java.util.HashSet;
import java.util.Set;
class LinkedList {
private Node head;
private Set<Integer> set;
public LinkedList() {
set = new HashSet<>();
}
public void add(int value) {
if (!set.contains(value)) {
set.add(value);
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
}
public boolean contains(int value) {
return set.contains(value);
}
}
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
class SortedLinkedList {
private Node head;
public SortedLinkedList() {
}
public void add(int value) {
Node newNode = new Node(value);
if (head == null || head.value >= value) {
newNode.next = head;
head = newNode;
} else {
Node current = head;
while (current.next != null && current.next.value < value) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
}
public boolean contains(int value) {
Node current = head;
int index = 0;
while (current != null) {
if (current.value == value) {
return true;
}
current = current.next;
index++;
}
return false;
}
}
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
总之,要提高Java链表类的查找效率,可以根据具体场景选择合适的数据结构和算法。在大多数情况下,使用哈希表是最简单且高效的方法。