在Java中,有序链表通常是指一个已经按照特定顺序(如升序或降序)排列的链表。这种数据结构在插入、删除和查找操作时非常高效。以下是一个简单的有序链表实现示例:
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class SortedLinkedList {
Node head;
public void insert(int data) {
Node newNode = new Node(data);
if (head == null || head.data >= data) {
newNode.next = head;
head = newNode;
} else {
Node current = head;
while (current.next != null && current.next.data< data) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
}
public void delete(int data) {
if (head == null) return;
if (head.data == data) {
head = head.next;
return;
}
Node current = head;
while (current.next != null && current.next.data != data) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
}
}
public boolean search(int data) {
Node current = head;
while (current != null) {
if (current.data == data) {
return true;
}
if (current.data > data) {
break;
}
current = current.next;
}
return false;
}
}
public class Main {
public static void main(String[] args) {
SortedLinkedList list = new SortedLinkedList();
list.insert(5);
list.insert(3);
list.insert(7);
list.insert(1);
System.out.println("Searching for 3: " + list.search(3)); // 输出:Searching for 3: true
System.out.println("Searching for 4: " + list.search(4)); // 输出:Searching for 4: false
list.delete(3);
System.out.println("Searching for 3 after deletion: " + list.search(3)); // 输出:Searching for 3 after deletion: false
}
}
这个简单的有序链表实现展示了如何在Java中创建和操作有序链表。在实际应用中,你可能需要根据具体需求对这个实现进行扩展和优化。