【发布时间】:2020-11-20 07:10:20
【问题描述】:
我正在尝试使用数组作为模拟循环链表来实现约瑟夫斯选举问题。
item 和 next 数组代表循环链表的节点。在每个第 M 个元素上,一个元素被标记为删除。下一个数组跳过标记的索引。
当数组中剩下一个元素时,我们打印出该元素和剩下的项目。
问题来自 Sedgewick C++ 算法书籍第三版。练习 3.31。
我得到的输出不正确,我没有迷路。
void array_represent_linked_list(int num_ints, int M) {
int* item = new int[num_ints];
int* next = new int[num_ints];
//populated item and next array with elements
for (int index = 0; index < num_ints; index++) {
item[index] = index + 1;
if (index == (num_ints - 1)) {
next[index] = 0;
}
else {
next[index] = index + 1;
}
}
int nums_left = num_ints;
int x = 0;
int count = 0;
int last_element_index = 0;
while ( nums_left > 1) {
//if current value divisible by M-2?
if ((count % M-2) == 0) {
if ((nums_left - 1) == 1) {
//record the next index which is the last element
last_element_index = next[x];
}
else {
//mark for removal of element from array
next[x] = next[next[x]];
}
nums_left -= 1;
}
//move to next element of array
x = next[x];
count++;
}
std::cout << item[last_element_index]<< " " << last_element_index<< std::endl;
}
输出
array_represent_linked_list(9,5); //item[x] =8 , next[x] = 7
【问题讨论】:
-
count % M-2可能不会像你认为的那样做 -
你试过调试吗?你的发现在哪里?
标签: c++ arrays algorithm data-structures linked-list