Я пытаюсь создать структуру данных Trie (школьная работа), и я использую список, который я также создал сам и работает нормально (проверено) для хранения N-узлов в Trie.
В любом случае, проблема в том, что каждый узел должен хранить список узлов, чтобы я мог создать свое N-арное дерево / дерево, но я попал в ловушку ...
Когда я отлаживаю и прохожу цикл для , я вижу, что currentNode все глубже проникает в мое дерево. Однако, когда я смотрю на него с точки зрения корня, у моего корня есть только один связанный список, содержащий первый узел, созданный в первой итерации цикла. Последовательные итерации не регистрируются в NODE в BRANCH ROOT NODE ... но он работает в currentNode, как если бы они были отдельными копиями, даже если currentNode - указатель на правильный (я надеюсь) узел.
Что-то не так с моим кодом?!? Я неправильно понимаю, как работают указатели ?? Помогите! Спасибо.
Моя структура узлов.
struct Node {
char letter;
ItemType item;
List<Node> * branches;
};
Node * root;
int size;
Моя функция пут.
ItemType put(KeyType newKey, ItemType newItem) {
Node * currentNode = root;
if (isEmpty()) {
//So build a new key
for (int levelIndex = 1; ((int) (newKey.length()) - levelIndex) >= 0; ++levelIndex) {
currentNode->branches = new List<Node>;
Node * tempNode = new Node;
tempNode->letter = newKey.at(levelIndex - 1);
currentNode->branches->add(*tempNode);
currentNode = tempNode;
}
//Store
currentNode->item = newItem;
++size;
return NULL; //The former item.
} else {
//Begin
return puttanesca(newKey, newItem, *(currentNode->branches), 1, 1);
}
}
Редактировать: О, извините, я забыл сказать, что puttanesca - это рекурсивная функция, которую я использую для перемещения и размещения узлов и прочего. Но я еще не успел это проверить, я застрял здесь, пытаясь добавить первый ключ в мой пустой Три из-за этой проблемы ...
Больше правок:
Вот puttanesca, я не думаю, что это как-то связано с проблемой, но ... это все равно.
Я нахожусь в процессе изменения указателя List в структуре Node на просто объект, поэтому некоторые из этих вещей могут выглядеть неправильно или просто неправильно, потому что я не очень хорош в C ++, и я У меня все еще есть проблемы, но общую концепцию / алгоритм можно увидеть ... О, и я использую typedef string KeyType для моего ключа только для некоторой проверки будущего и шаблона для ItemType .
ItemType puttanesca(KeyType newKey, ItemType newItem, List<Node> & tempList, int listIndex, int levelIndex) {
Node currentNode = tempList.get(listIndex);
//Am I at the right node? (searching)
if (newKey.at(levelIndex - 1) == currentNode.letter) { //Yes, I am.
//Is this a leaf node?
if (currentNode.branches == NULL) {
//Key does not already exist
if (newKey.length() != levelIndex) {
//So build a new key
for (; ((int) (newKey.length()) - levelIndex) >= 0; ++levelIndex) {
currentNode.branches = new List<Node>;
Node * tempNode = new Node;
tempNode->letter = newKey.at(levelIndex - 1);
currentNode.branches.add(*tempNode);
currentNode = *tempNode;
}
//Store
currentNode.item = newItem;
++size;
return NULL; //The former item.
} else { //Key matched!
//Replace with new item
ItemType currentItem = currentNode.item;
currentNode.item = newItem;
return currentItem; //which is actually the now old item after the previous statement
}
} else { //Not a leaf, keep going
//Go to the next level and start from the first index
ItemType currentItem = puttanesca(newKey, newItem, currentNode.branches, 1, levelIndex + 1);
if (currentItem == NULL) {
//Key found to be inexistant
//So build a new key - create new sibling
Node * tempNode = new Node;
tempNode->letter = newKey.at(levelIndex - 1);
currentNode.branches.add(*tempNode);
currentNode = *tempNode;
//Continue building key - extend sibling
for (++levelIndex; ((int) (newKey.length()) - levelIndex) >= 0; ++levelIndex) {
currentNode.branches = new List<Node>;
Node * tempNode = new Node;
tempNode->letter = newKey.at(levelIndex - 1);
currentNode.branches.add(*tempNode);
currentNode = *tempNode;
}
//Store
currentNode.item = newItem;
++size;
return NULL; //The former item
} else {
return currentItem; //The former item;
}
}
} else { //Wrong node
if (tempList.getLength() > listIndex) {
return puttanesca(newKey, newItem, tempList, ++listIndex, levelIndex);
} else {//End of the line, chump
return NULL; //Tell parent you failed
}
}
}