下列程序是C语言现代方法中add_to_list函数的,完整代码,
/***************************************************************************
This program is realize add new node before the liseadd_to_list.c
****************************************************************************/
#include<stdio.h>
#include<stdlib.h>
//define a struct of node
struct node{
int value; //data stored in the node
struct node *next; //pointer to the next node
};
int display(struct node *q);
int main(void)
{
struct node *first=NULL;//initial the node
char choise; //define choise for circulate
do{ //circulate to add new node for the list
struct node *new_node=malloc(sizeof(struct node));
printf("Enter number you want to add to the list \n");
scanf("%d",&new_node->value);
getchar(); //clear up '\n' for next scanf
// printf("%d\n",new_node->value);
new_node->next=first;
first=new_node;
printf("Add next node?(y/n?)");
scanf("%c",&choise);
getchar(); //clear up '\n' for next scanf
}while(choise=='y'||choise=='Y');
display(first);
return 0;
}
int display(struct node *p)
{
while(p!=NULL)
{
printf("%d->",p->value);
p=p->next;
}
printf("NULL\n");
return 0;
}
实现效果:
Enter number you want to add to the list
10
Add next node?(y/n?)y
Enter number you want to add to the list
20
Add next node?(y/n?)y
Enter number you want to add to the list
30
Add next node?(y/n?)y
Enter number you want to add to the list
40
Add next node?(y/n?)y
Enter number you want to add to the list
50
Add next node?(y/n?)n
50->40->30->20->10->NULL
总结:
1、在display函数的实现上,传递的是一个地址,此地址不是指针的地址,而是指针所指向的地址,故传递的是first而不是&first。
2、scanf是读取数据缓冲区的数据流,scanf调用前键盘输入的字符都存储到缓冲区中,直到遇到回车符(回车符也存入缓冲区),开始调用scanf函数,读取缓冲区的相匹配的内容。(注意:是相匹配的内容。)如若没有读完缓冲区的内容,留在下次sanf函数读取。%c会读取回车符,故在读取char类型前使用getchar清除缓冲区值。%d不匹配回车符,会把它丢弃。
关于scanf的进一步理解可以看看下列代码:
int main()
{
char a,b,c,f;
int d;
scanf("%c%c",&a,&b);//输入qw↓(↓代表回车符),此时缓冲区内容qw↓,qw分别被a,b读取,↓留在缓冲区,读取后缓冲区内容:↓
printf("a=%c,b=%c\n",a,b);//输出a=q,b=w
scanf("%d",&d); //读取缓冲区↓,由于不与%d匹配故丢弃,此时缓冲区为空,要求用户再次输入内容,输入123↓,123被d读取后,缓冲区只剩下↓
printf("d=%d",d); //输出d=123
scanf("%c",&c); //重点来了,此时读取缓冲区内容↓,因为是%c类型的,所以回车符有效,这是用户就不能输入c的内容了,自动获取了回车符,如若希望用户键入,可在此句前用getchar()清除‘↓’字符。
printf("c=%c",c);//打印出c=
scanf("%c",&f);// 此时缓冲区为空,要求用户输入新的值,输入abc↓,a被f读取,此时缓冲区剩下bc↓
printf("f=%c",f);//输出f=a
return 0;
}