Created
September 24, 2021 16:28
-
-
Save yeputons/4b0b64bc1c2d9ba01fffa660f48b9a08 to your computer and use it in GitHub Desktop.
Indices vs pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct node { | |
int value; // Данные в узле | |
int prev = -1; // Номер предыдущего узла в массиве | |
int next = -1; // Номер следующего узла в массиве | |
}; | |
node nodes[1'000'000]; // Завели себе миллион нод | |
int main() { | |
nodes[1].value = 10; | |
nodes[1].prev = -1; | |
nodes[1].next = 3; | |
nodes[3].value = 11; | |
nodes[3].prev = 1; | |
nodes[3].next = 2; | |
nodes[2].value = 12; | |
nodes[2].prev = 3; | |
nodes[2].next = -1; | |
int head = 1; // Начало списка | |
for (int i = head; i != -1; i = nodes[i].next) { | |
std::cout << nodes[i].value << "\n"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct node { | |
int value; // Данные в узле | |
node *prev = | |
nullptr; // Указатель на предыдущий узел (необязательно в массиве) | |
node *next = | |
nullptr; // Указатель на следующий узел (необязательно в массиве) | |
}; | |
node nodes[1'000'000]; // Завели себе миллион нод | |
int main() { | |
nodes[1].value = 10; | |
nodes[1].prev = nullptr; | |
nodes[1].next = &nodes[3]; | |
nodes[3].value = 11; | |
nodes[3].prev = &nodes[1]; | |
nodes[3].next = &nodes[2]; | |
nodes[2].value = 12; | |
nodes[2].prev = &nodes[3]; | |
nodes[2].next = nullptr; | |
node *head = &nodes[1]; // Начало списка | |
// Теперь вообще неважно, где живут ноды: мы не пишем nodes[]. | |
for (node *cur = head; cur != nullptr; cur = cur->next) { | |
std::cout << cur->value << "\n"; | |
// Ещё можно так, но это длиннее. | |
std::cout << (*cur).value << "\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment