#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include “kernel_list.h”
//定义大结构体
struct big_list_t
{
int num;
struct list_head list;
};
//定义内核链表的头结点为全局变量
struct list_head *head;
//插入数据 参数为需要插入的数据
static void insert_node(int date)
{
struct big_list_t *new = (struct big_list_t *)
malloc(sizeof(struct big_list_t));
if( new == NULL )
{
printf(“malloc fail\n”);
return ;
}
new->num = date;
list_add_tail(&new->list,head);
}
//展示链表中的数据
static void show_node()
{
struct list_head *pos = head->next;
list_for_each(pos,head)
{
struct big_list_t *tmp = list_entry(
pos, struct big_list_t, list);
printf("%d\n", tmp->num);
}
}
//删除表中的数据
static void delete_node(int n)
{
struct list_head *pos = head->next;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, head)
{
struct big_list_t *tmp = list_entry(
pos, struct big_list_t, list);
if(tmp->num == n)
{
list_del(pos);
free(tmp);
}
}
}
//修改数据
static void change_node(int olddate, int newdate)
{
struct list_head *pos = head->next;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, head)
{
struct big_list_t *tmp = list_entry(
pos, struct big_list_t, list);
if(tmp->num == olddate)
{
tmp->num = newdate;
}
}
}
int main(void)
{
head = (struct list_head*)malloc(
sizeof(struct list_head));
//初始化内核链表的头结点
INIT_LIST_HEAD(head);
while(1)
{
printf("select: 1.add 2.show 3.delete 4.change\n");
int chose;
fscanf(stdin,"%d",&chose);
switch(chose)
{
case 1:
{
int num;
printf("input num:\n");
fscanf(stdin,"%d",&num);
insert_node(num);
break;
}
case 2:
{
show_node();
break;
}
case 3:
{
int num;
printf("input change_node\n");
fscanf(stdin, "%d", &num);
delete_node( num );
break;
}
case 4:
{
//输入需要修改的数据
printf("input change number\n");
int oldnum;
fscanf(stdin, "%d", &oldnum);
//输入修改后的数据
printf("input new number\n");
int newnum;
fscanf(stdin, "%d", &newnum);
change_node(oldnum, newnum);
break;
}
defalt:
{
printf("input fail,select again\n");
break;
}
}
}
}