单链表操作

1. 嵌入式C语言中链表的应用场景

      链表在FreeRTOS和RT_Thread等操作系统中属于比较核心的部分,常用链表实现队列,任务间通信,任务对象管理等操作,此节主要介绍单链表的常用操作。  

2. 创建及插入单向链表

 

fig1. 空链表直接插入新成员

fig2. 非空链表找到NULL从尾部插入 

struct mate{
	char *name;
	int age;
	struct mate *next;
};

//定义链表头结构体
struct list{
	char *name;
	struct mate *next;
};
//链表初始化
void InitList(struct list *pList, char *name)
{
	pList->name = name;
	pList->next = NULL;
}
//加入链表新成员
void AddItemToList(struct list *pList, struct mate *new_mate)
{
	struct mate *last;
	if(pList->next == NULL)//开始为空链表则直接加入新成员
	{
		pList->next = new_mate;
		new_mate->next = NULL;
		return;
	}
	last = pList->next;
	while(last->next)//找到最后一项
	{
		last = last->next;
	}
	last->next = new_mate;
	new_mate->next = NULL;
}

3. 删除单向链表

fig3. (特殊情况) 第一项为待删除项 

 fig4. 其他项为待删除项

void DelItemFormList(struct list *pList,struct mate *delmate)
{
    struct mate *p = pList->next;
    struct mate *pre = NULL;
    while(NULL != p && p != delmate)//未找到,后移下一个成员
    {
	    pre = p;
	    p = p->next;
    }
    /**退出的条件:p为空或者p为要删除的成员***/
    if(NULL == p)//空,无要删除的成员
    {
	    printf("can not find the mate to del.\r\n");
	    return;
    }
    if(NULL == pre) //pre未被赋值,要删除的是第一项
    { 
	    pList->next = p->next;
    }
    else{
	    pre->next = p->next;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值