简体   繁体   中英

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. Yet it is iterating 6 times. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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