要實現一個有序雙向鏈表,可以按照以下步驟進行:
class Node {
Node prev;
int value;
Node next;
}
class SortedDoublyLinkedList {
Node head;
Node tail;
}
void insert(int value) {
Node newNode = new Node();
newNode.value = value;
if (head == null) {
head = newNode;
tail = newNode;
} else {
Node current = head;
while (current != null && current.value < value) {
current = current.next;
}
if (current == head) {
newNode.next = head;
head.prev = newNode;
head = newNode;
} else if (current == null) {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
} else {
newNode.prev = current.prev;
newNode.next = current;
current.prev.next = newNode;
current.prev = newNode;
}
}
}
void remove(int value) {
if (head == null) {
return;
}
Node current = head;
while (current != null && current.value != value) {
current = current.next;
}
if (current == head) {
head = head.next;
if (head != null) {
head.prev = null;
} else {
tail = null;
}
} else if (current == tail) {
tail = tail.prev;
tail.next = null;
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}
這樣就可以實現一個基本的有序雙向鏈表,在插入和刪除節點時能夠保持鏈表的有序性。