使用列表向后打印字母表时缺少'a'
'a' is missing when printing alphabet backwards with lists
我正在尝试使用链表向后打印字母表,但我无法显示"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
的情况,因此循环永远不会终止,或者更有可能得到分段错误。
for(size_t i = 25; i >= 0; i--)
"a"是字符串中的索引 0,您永远不会获得索引 0。
相关文章:
- 如何在C++中移动字母表中的字母?
- 循环回到z之后的字母表的开头
- 删除单链表列表
- C++ 链表列表运算符[]
- C 分类字符串按大小和字母表
- 我在使用布尔函数时遇到问题,其中用户输入两个字母并输出字母表中最高的字母
- 如何在C++中创建链表列表?
- 使用列表向后打印字母表时缺少'a'
- 警告:数组"字母表"由括号字符串文本初始化
- 如何检查字符是否是某个字母表中的字母
- 为什么在此 C 代码中将字母表拆分为多个范围?
- c++如何确定字母表中一个单词是否在另一个单词之前
- 计算C++中每个字母表的出现次数
- 求字母表{a,b,c}上长度为n的字符串w的个数
- 如何检查字母表中的字母在文本文件中出现的次数C++
- 将莫尔斯值解码为字母表
- 在 C 语言中,求解从字母表中输入的整数并重复循环
- 使用具有非类表数据和非表/列表UI的Qt模型/视图
- 迭代C/C++中的字母表
- 制作一个程序来计算字母表中每个字母的出现次数