Я пытаюсь распечатать алфавит назад, используя связанные списки, но я не могу получить "а", чтобы показать. По какой-то причине он пропускает его, и я не могу понять это. Вот мой код:
int _tmain(int argc, _TCHAR* argv[])
{
char s[]="abcdefghijklmnopqrstuvwxyz";
node *head;
node *temp;
node *current;
head = new node; // create the head of the linked list
head->data = s[25];
head->next = NULL;
temp = head; // get ready for the loop - save the head in temp - you are going to change temp in the loop
for(size_t i = 25; i >= 1; i--) // create the rest of the linked list
{
current = new node; // make a new node
current->data = s[i]; // set it data member
current->next = NULL;
temp->next = current; // point to the new node
temp = current; // make temp point to current node (for next time through)
}
node *ptr = head; // set a ptr to head, then you are going to "increment" the pointer
while (ptr != NULL)
{
cout << ptr->data; // print out the linked list
ptr = ptr->next; // increment the linked list
}
cout << endl;
system("pause");
return 0;
}
кто-нибудь знает, почему это происходит? Я думаю, что что-то не так в моей петле. Спасибо!
Проблема в том, что вы не учитываете случай i=0
из цикла for.
Измените цикл for
на это:
size_t i = 25; // 'z' was already added
do
{
--i;
current = new node; // make a new node
current->data = s[i]; // set it data member
current->next = NULL;
temp->next = current; // point to the new node
temp = current; // make temp point to current node (for next time through)
} while ( i != 0 );
Причина, по которой вы не можете просто сделать for(size_t я = 25; я >= 0; i--)
состоит в том, что i
без знака, и поэтому всегда будет иметь место i >= 0
и, следовательно, цикл никогда не завершится, или, скорее всего, вы получите ошибку сегментации.
for(size_t i = 25; i >= 0; i--)
'a' - это индекс 0 в вашей строке, вы никогда не получите индекс 0.