内核链表编程代码

#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;
		}
	}
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值