C语言的链表的一个问题
typedef struct
{
int data;
struct Node *next;
}Node;
typedef Node * LinkList;
LinkList creatLinkList_2()
{
LinkList pRear,pHead,pCur;
int num;
printf("creating pHead...\n");
if( ( pHead = (LinkList)malloc(sizeof(Node)) ) == NULL)
{
printf("failed to allocate memery for pHead");
}
else
{
printf("successfully create pHead!\n");
}
pHead->next = NULL;
pRear = pHead;
while(1)
{
printf("input the number of linklist you want to create:");
printf("(-1 as end )\n");
scanf("%d\n",&num);
if(num == -1)
{
printf("finish creating linklist!");
break;
}
pCur = (LinkList)malloc(sizeof(Node));
pCur->data = num;
pRear->next = pCur;
pRear = pCur;
printf("%n");
}
pRear->next = NULL;
return pHead;
}
void printLinkList(LinkList pHead)
{
LinkList p = pHead;
while(p->next)
{
p = p->next;
printf("your linklist is:%d\n", p->data);
}
}
int main()
{
/* LinkList *L = (LinkList *)malloc(sizeof(LinkList));
create_LinkList(&L,5);
LinkList p = *L;
show_LinkList(p,5);
free(L);*/
LinkList pMyList = creatLinkList_2();
// printf("hehe");
printLinkList(pMyList);
return 0;
}
程序基本没大问题,主要是当输入提示出现后,必须输入2次数字才能进入循环,这是为何,同样,输入2次-1才能退出循环,大家去机子上跑一下如果方便的话,帮我修复一下,我用的是LINUX
printf("请输入数字");
scanf("%d",&num);
while(1)
{
//创建链表
if(num == -1)
退出循环
}
[解决办法]
在每个最后不带\n的printf后面加fflush(stdout);
在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin);
另外请检查scanf的返回值。
[解决办法]
LinkList creatLinkList_2()
{
LinkList pRear,pHead,pCur;
int num, data;
printf("creating pHead...\n");
if ( (pHead = (LinkList)malloc(sizeof(Node))) == NULL)
{
printf("failed to allocate memery for pHead");
return NULL;
}
else
{
printf("successfully create pHead!\n");
}
pHead->next = NULL;
pRear = pHead;
printf("input the number of the node int the linklist you want to create:");
printf("(-1 as end )\n");
scanf("%d\n",&num);
if(num <= -1)
{
printf("finish creating linklist!");
pHead->data = 0;
return pHead;
}
pHead->data = num;
while(num-- >0 )
{
pCur = (LinkList)malloc(sizeof(Node));
if (!pCur) {
pHead->data -= num+1;
break;
}
scanf("%d",&data);
pCur->next = NULL;
pCur->data = data;
pRear->next = pCur;
pRear = pCur;
}
pRear->next = NULL;
return pHead;
}