单链表实例之学生系统
#include<stdio.h>
#include<stdlib.h>
#define NAME_LEN 20
typedef struct node {
int number;
char *name;
struct node *next;
} node_t;
node_t *g_head;
int add_stu() {
node_t *new, *tmp;
tmp = g_head;
char *name;
new = (node_t *)malloc(sizeof(node_t));
if (new == NULL) {
printf("malloc new node fail.\n");
return -1;
}
new->name = (char *)malloc(NAME_LEN);
if (new->name == NULL) {
printf("malloc new node name fail.\n");
return -1;
}
printf("input student number:");
scanf("%d", &new->number);
printf("input student name:");
scanf("%s", new->name);
if (g_head == NULL) {
g_head = new;
} else {
while(tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new;
new->next = NULL;
}
printf("input student success.\n");
return 0;
}
int input_stu()
{
int choose;
printf("1.input student message.\n");
printf("2.back.\n");
while (1) {
printf("please choose:");
scanf("%d", &choose);
switch (choose) {
case 1:
add_stu();
break;
case 2:
return -1;
break;
default:
printf("error.\n");
}
printf("1.input student message.\n");
printf("2.back.\n");
}
return 0;
}
int output_stu()
{
char *name;
int number;
node_t *new, *tmp;
tmp = g_head;
if (g_head == NULL) {
printf("Student system is null.\n");
} else {
while (tmp != NULL) {
printf(" %d ", tmp->number);
printf(" %s \n", tmp->name);
tmp = tmp->next;
}
}
return 0;
}
int destroy_list()
{
printf("start destroy list.\n");
node_t *list, *tmp;
list = g_head;
while (list != NULL) {
tmp = list;
free(tmp->name);
free(tmp);
list = list->next;
}
printf("destroy list success.\n");
return 0;
}
int main()
{
char c;
int choose;
printf("Student system.\n");
printf("1.input student message.\n");
printf("2.output student message.\n");
printf("3.exit.\n");
printf("please choose:");
scanf("%d", &choose);
while (1) {
if (choose == 3) {
break;
}
switch (choose) {
case 1:
input_stu();
break;
case 2:
output_stu();
break;
default:
printf("error.\n");
}
printf("1.input student message.\n");
printf("2.output student message.\n");
printf("3.exit.\n");
printf("please choose:");
scanf("%d", &choose);
}
destroy_list();
return 0;
}
运行结果演示:
1、复制代码到main.c文本中。
2、在linux系统下编译成可执行文件main,gcc main.c -o main。
3、编译目录下执行./main运行。