나는 노드를 찾고 싶을 때마다 목록의 머리부터 시작하는 것을 피할 방법을 찾고 있었기 때문에 노드에 인덱스를 할당하고 무작위 (정확히 무작위는 아니며 아래 참조) 노드에 포인터를 유지할 것을 고려했다. 찾을 인덱스에 가장 가까운 포인터를 찾습니다. 코드로 설명하도록 허용 :링크 된 목록 :이 솔루션이 좋습니까?
// head and last are pointers to the first and last items of a doubly-linked list
// current is a pointer that will change over time. It's used as a temporary pointer
template <class T>a
Node<T>* List<T>::get_closest(Node<T> node, int& difference) {
int curr_to_i = current->index - node->index;
int last_to_i = last->index - node->index;
Node* closest = node->index < abs(curr_to_i) ? head : current;
closest = closest->index < abs(last_to_i) ? closest : last;
difference = closest->index - node->index;
return closest;
}
/*
* This functions adds a node with the given value to the given index. The node at that
* index and all the following are moved, and the new node is inserted before them.
*/
template <class T>
bool List<T>::add(T value, int index) {
if (index < 0) { //Invalid index
return false;
} else if (index == last->index +1) {
push(value);
return true;
} else if (index > 0) {
Node* new_n = new Node;
new_n->value = value;
new_n->index = index;
int difference;
Node* closest = get_closest(new_n, difference);
if (difference < 0) {
for (int i = 0; i < abs(difference); i++) {
current = current->previous;
}
} else if (difference > 0) {
for (int i = 0; i < abs(difference); i++) {
current = current->next;
}
} /* current now points to the node we want to move */
new_n->previous = current->previous;
new_n->next = current;
current->previous->next = new_n;
current->previous = new_n;
if (index == 0) {
root = new_n;
}
new_n = new_n->next;
while (new_n != null) {
new_n->index++;
new_n = new_n->next;
}
return true;
}
}
머리에서 시작하여 앞으로 몇 번 앞으로 나아가는 것보다 효율적입니까?
문맥없이 대답하기가 어렵다 ... "건너 뛰기 목록"처럼 들린다. – diapir