使用列表向后打印字母表时缺少'a'

'a' is missing when printing alphabet backwards with lists

本文关键字:字母表 列表 打印      更新时间:2023-10-16

我正在尝试使用链表向后打印字母表,但我无法显示"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。