Это было бы более ясным и видимым рассмотрим следующую показательной программы
#include <iostream>
int main()
{
const size_t N = 10;
int a[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
while (true)
{
std::cout << "\nEnter the size of the sub array less than or equal to "
<< N << " (0 - exit): ";
size_t n = 0;
std::cin >> n;
if (!n) break;
if (N < n) n = N;
size_t i = 0;
for (size_t j = 0; j < n && ++j < n && ++j < n;) i++;
for (size_t j = 0; j < n; j++) std::cout << a[j] << ' ';
std::cout << std::endl;
std::cout << a[i] << std::endl;
}
}
Его выход
Enter the size of the sub array less than or equal to 10 (0 - exit): 10
0 1 2 3 4 5 6 7 8 9
4
Enter the size of the sub array less than or equal to 10 (0 - exit): 9
0 1 2 3 4 5 6 7 8
4
Enter the size of the sub array less than or equal to 10 (0 - exit): 8
0 1 2 3 4 5 6 7
3
Enter the size of the sub array less than or equal to 10 (0 - exit): 7
0 1 2 3 4 5 6
3
Enter the size of the sub array less than or equal to 10 (0 - exit): 6
0 1 2 3 4 5
2
Enter the size of the sub array less than or equal to 10 (0 - exit): 5
0 1 2 3 4
2
Enter the size of the sub array less than or equal to 10 (0 - exit): 4
0 1 2 3
1
Enter the size of the sub array less than or equal to 10 (0 - exit): 3
0 1 2
1
Enter the size of the sub array less than or equal to 10 (0 - exit): 2
0 1
0
Enter the size of the sub array less than or equal to 10 (0 - exit): 1
0
0
Enter the size of the sub array less than or equal to 10 (0 - exit): 0
Таким образом, вы можете увидеть себя, какой элемент будет outputed, когда есть четное или нечетное элементов в массиве.
Как переписать код для списка?
Это может выглядеть следующим образом
node *slowptr = head;
for (node * fastptr = head;
fastptr && (fastptr = fastptr->next) && (fastptr = fastptr->next);)
{
slowptr = slowptr->next;
}
Этот цикл можно записать еще проще, если вы будете проверять перед циклом, что head
не равна NULL
Например
node *slowptr = head;
if (slowptr)
{
for (node * fastptr = head;
(fastptr = fastptr->next) && (fastptr = fastptr->next);)
{
slowptr = slowptr->next;
}
}
Что касается цикла, который вы показали, то это неверно
while (fastptr->next->next != NULL && slowptr->next != NULL)
fastptr
и fastptr->next
каждый может быть равен NULL. Таким образом, код имеет неопределенное поведение.
Ваш код сработает, если 'fastptr-> next == NULL'. – Quentin
Попробуйте в некоторых случаях и посмотрите, что произойдет. –
Вы спрашиваете, какой из них ваш код ** будет ** говорить в середине? Или какой из них ваш код ** должен ** сказать посередине? Первое достаточно легко определить. Второй - ваш выбор. – Teepeemm