c语言链表的头插法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _NODE
{
int s_age;
char s_name[128];
struct _NODE * next;
};
struct _NODE * CreateList(void)
{
struct _NODE * phead = NULL;
return phead;
}
void PrintList(struct _NODE * phead)
{
struct _NODE * ptmp = phead;
while (ptmp)
{
printf(“age %d\n”, ptmp->s_age);
printf(“name %s\n”, ptmp->s_name);
ptmp = ptmp->next;
}
}
struct _NODE * AddNode(struct _NODE * phead, int age, char * name)
{
if (phead == NULL)
{
struct _NODE * new = (struct _NODE *) malloc(1 * sizeof(struct _NODE));
new->s_age = age;
strcpy(new->s_name, name);
new->next = NULL;
phead = new;
return phead;
}
else
{
struct _NODE * new = (struct _NODE *) malloc(1 * sizeof(struct _NODE));
new->s_age = age;
strcpy(new->s_name, name);
new->next = NULL;
new->next = phead->next;
phead->next = new;
return phead;
}
}
int main(void)
{
int age;
char name[20];
int i = 0;
struct _NODE * list = CreateList();
while (i < 3)
{
printf("age:\n");
scanf("%d", &age);
getchar();
printf("name :\n");
gets(name);
list = AddNode(list, age, name);
i++;
}
PrintList(list);
system("pause");
}