简体   繁体   English

当使用while循环遍历链接列表时,为什么我的循环迭代列表中节点数的两倍?

[英]When using a while loop to traverse a linked list, why does my loop iterate by twice the number of nodes in the list?

Here's the code. 这是代码。 When I run it with input such as sadx, where x ends the input loop, I get the output s 0 1a 2 3d 4 5. As far as I can tell it should only iterate 3 times. 当我使用诸如sadx之类的输入来运行它时,x结束了输入循环,我得到了输出s 0 1a 2 3d 4 5。据我所知,它应该仅迭代3次。 Yet it is iterating 6 times. 然而,它迭代了6次。 I do not see how this could be. 我不知道这怎么可能。

#include<stdio.h>

typedef struct node
{
        char alpha;
        struct node *next;
} *nodePtr;

nodePtr make_node(char a);

int main(void)
{
    nodePtr head, np, last;
    char c;
    head = NULL;
    scanf("%c", &c);
    while(c != 'x')
    {
       np = make_node(c);
       if(head == NULL)
          head = np;
       else
          last->next = np;
       last = np;
       scanf("%c", &c);
    }
    np = head;
    int n = 0;
    while(np != NULL)
    {
       printf("%c %d", np->alpha, n);
       np = np->next;
       n++;
    }
    return 0;
}

nodePtr make_node(char a)
{
    nodePtr np = (nodePtr)malloc(sizeof(struct node));
    np->alpha = a;
    np->next = NULL;
    return np;
}

scanf("%c", &c); won't skip spaces. 不会跳过空格。 You're building a list with 6 nodes, 3 of which contain spaces. 您正在建立一个包含6个节点的列表,其中3个包含空格。

在scanf中的“%c”之前添加一个空格,这样它将跳过空格,例如每行末尾的换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM