gpt4 book ai didi

c++ - 使用列表向后打印字母表时缺少“a”

转载 作者:行者123 更新时间:2023-11-28 07:04:05 25 4
gpt4 key购买 nike

我正在尝试使用链表向后打印字母表,但无法显示“a”。出于某种原因,它跳过了它,我无法弄清楚。这是我的代码:

    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's 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;
}

有人知道为什么会这样吗?我认为我的 for 循环有问题。谢谢!

最佳答案

问题是您在 for 循环中遗漏了 i=0 的情况。

将您的 for 循环更改为:

    size_t i = 25; // 'z' was already added
do
{
--i;
current = new node; // make a new node
current->data = s[i]; // set it's 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 i = 25; i >= 0; i--) 的原因是因为 i 是无符号的,所以它i >= 0 总是这样,因此循环永远不会终止,或者更有可能出现段错误。

关于c++ - 使用列表向后打印字母表时缺少“a”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22027981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com