要提高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鏈表類的查找效率,可以根據具體場景選擇合適的數據結構和算法。在大多數情況下,使用哈希表是最簡單且高效的方法。