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

时间:2014-01-30 03:08:56

标签: c linked-list

这是代码。 当我使用诸如s和d x之类的输入运行它时,其中x结束输入循环, 我得到输出s 0 1a 2 3d 4 5.据我所知它应该只迭代3次。 然而它迭代了6次。我不明白这是怎么回事。

#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;
}

2 个答案:

答案 0 :(得分:1)

scanf("%c", &c);不会跳过空格。您正在构建一个包含6个节点的列表,其中3个节点包含空格。

答案 1 :(得分:1)

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