C语言的链表的一个问题

tankey0909 2013-01-17 03:36:42

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)
退出循环
}
...全文
130 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
DyanWang 2013-01-21
  • 打赏
  • 举报
回复
scanf 放入 '\n' 的问题.
prajna 2013-01-17
  • 打赏
  • 举报
回复


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;
}
tankey0909 2013-01-17
  • 打赏
  • 举报
回复
引用 1 楼 zhao4zhong1 的回复:
在每个最后不带\n的printf后面加fflush(stdout); 在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin); 另外请检查scanf的返回值。
引用 1 楼 zhao4zhong1 的回复:
在每个最后不带\n的printf后面加fflush(stdout); 在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin); 另外请检查scanf的返回值。
问题没有解决
赵4老师 2013-01-17
  • 打赏
  • 举报
回复
在每个最后不带\n的printf后面加fflush(stdout); 在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin); 另外请检查scanf的返回值。

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧