#include<stdio.h>
#include<stdlib.h>
struct node //定义结构
{
int num;
char name[10];
struct node * next; //指向向一个结点
};
typedef struct node Node; //相当于类型重命名
typedef struct node * Link;
void create_head(Link *head)
{
*head = NULL;
}
void create_new_node(Link * new_node)
{
*new_node = (Link)malloc(sizeof(Node)); //分配空间
}
void is_malloc_ok(Link new_node)
{
if(new_node == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}
void insert_head(Link *head,Link new_node)
{
new_node -> next = *head;
*head = new_node;
}
void insert_tail(Link *head,Link new_node)
{
Link p;
p = *head;
if(*head == NULL) //为空情况
{
*head = new_node;
(*head) -> next = NULL;
}
else
{
while(p -> next != NULL) //尾插转换
{
p = p -> next;
}
p -> next = new_node;
new_node -> next = NULL;
}
}
void display(Link head)
{
Link p;
p = head;
if(head == NULL)
{
printf("The Link is empty!\n");
}
else
{
while(p != NULL)
{
printf("%d\t",p -> num);
printf("%s\n",p -> name);
p = p -> next;
}
}
}
int main()
{
int n,i,num1;
Link head;
Link new_node;
create_head(&head);
printf("Please enter the number in total:\n");
scanf("%d",&n);
for(i = 0; i < n; i++)
{
create_new_node(&new_node); //创建一个新的结点
is_malloc_ok(new_node); //判断是否分配成功
printf("Please input the name:\n");
scanf("%s",new_node -> name);
new_node -> num = (i + 1); //赋值num成员
//insert_head(&head,new_node); //头插
insert_tail(&head,new_node); //尾插
display(head); //显示
}
}