链表(c语言实现)--------------小练习
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
#define MIN_SIZE 32
struct role
{
int number;
char name[MAX_SIZE];
char sex[MIN_SIZE];
int age;
struct role *next;
};
struct role *creat()
{
struct role *p = NULL;
struct role *head = NULL;
struct role *tail = NULL;
p = (struct role *)malloc(sizeof(struct role));
printf(" 请输入编号,按0即退出
");
printf("编号->");
scanf("%d", &(p->number));
if (p->number == 0)
return head;
while (p->number != 0)
{
printf("姓名->");
scanf("%s", p->name);
printf("性别->");
scanf("%s", p->sex);
printf("年龄->");
scanf("%d", &(p->age));
if (head == NULL)
{
head = p;
tail = p;
}
else
{
tail->next = p;
tail = p;
}
p = (struct role *)malloc(sizeof(struct role));
printf("请输入编号,按0即退出
");
printf("编号->");
scanf("%d", &(p->number));
}
tail->next = NULL;
free(p);
return head;
}
void display(struct role *head)
{
struct role *p = head;
printf("编号 姓名 性别 年龄
");
while (p != NULL)
{
printf("%-16d%-16s%-16s%-16d
",
p->number, p->name, p->sex, p->age);
p = p->next;
}
}
int main(void)
{
struct role *head = creat();
display(head);
return 0;
}
需要改进的还很多.
这仅仅是练习~~~~
数据结构,我来了.加油!!!
小小的修改下...(其实就是free几下...咳咳..新人,,见笑了...)
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 50
#define MIN_SIZE 32
struct role
{
int number;
char name[MAX_SIZE];
char sex[MIN_SIZE];
char address[MAX_SIZE];
int age;
struct role *next;
};
struct role *creat()
{
struct role *head = NULL;
struct role *p = NULL;
struct role *tail = NULL;
p = (struct role *)malloc(sizeof(struct role));
printf("请输入编号,按0退出
");
printf("编号->");
scanf("%d", &(p->number));
if (0 == p->number)
{
free(p);
return 0;
}
while (0 != p->number)
{
printf("姓名->");
scanf("%s", p->name);
printf("性别->");
scanf("%s", p->sex);
printf("地址->");
scanf("%s", p->address);
printf("年龄->");
scanf("%d", &(p->age));
if (NULL == head)
{
head = p;
tail = p;
}
else
{
tail->next = p;
tail = p;
}
p = (struct role *)malloc(sizeof(struct role));
printf("请输入编号,按0退出
");
printf("编号->");
scanf("%d", &(p->number));
}
tail->next = NULL;
free(p);
return head;
}
void display(struct role *head)
{
struct role *p = NULL;
p = head;
printf("编号 姓名 性别 住址 年龄
");
while (NULL != p)
{
printf("%-16d%-16s%-16s%-16s%-16d",
p->number, p->name, p->sex, p->address, p->age);
p = p->next;
}
}
int main(void)
{
struct role *head = NULL;
head = creat();
display(head);
return 0;
}
最后.因为是练习,所以也没想用多文件...呼..不过这样看起来确实很乱...O.O