【发布时间】:2015-04-02 17:51:55
【问题描述】:
我正在尝试将节点添加到链表的开头。程序要求用户输入他想输入的名字的数量,所以如果我输入 3,它应该要求我输入 3 个不同的名字并将它们显示在一个列表中,而不是程序重复打印相同的名字。
struct node{
char data[20];
struct node* link;
}Damn;
struct node* head;
//Insert
void Insert(char p[20]){
struct node* temp = (struct node*) malloc(sizeof(struct node));
strncpy(Damn.data, p);
temp->link = head;
head = temp;
}
//Print
void Print()
{
struct node* temp = head;
while(temp != NULL){
printf(" %s \n", Damn.data );
temp = temp->link;
}
}
//Main
int main(){
head = NULL;
int i, n;
char p[20];
printf("How many names you want to enter\n");
scanf("%d", &n);
for(i=1; i<(n+1); i++){
printf("Enter the %dth name", i);
scanf("%s", p);
Insert(p);
Print();
}
【问题讨论】:
标签: data-structures struct linked-list nodes