在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中創建和操作有序鏈表。在實際應用中,你可能需要根據具體需求對這個實現進行擴展和優化。