[英]When using a while loop to traverse a linked list, why does my loop iterate by twice the number of nodes in the list?
這是代碼。 當我使用諸如sadx之類的輸入來運行它時,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;
}
scanf("%c", &c);
不會跳過空格。 您正在建立一個包含6個節點的列表,其中3個包含空格。
在scanf中的“%c”之前添加一個空格,這樣它將跳過空格,例如每行末尾的換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.