mcu芯片编程c语言用链表吗,C语言实现链表操作的例程

Node Pnode;

void SListInit(SList* s)

{

s->_pHead = NULL;

}

//构建一个结点

PNode BuySListNode(SDataType _data)

{

PNode node = (PNode)malloc(sizeof(Node));

if (node)

{

node->_data = _data;

node->_PNext = NULL;

}

return node;

}

/*

尾插,首先要创建一个新节点,然后判断链表当前是否有节点,若没有,则直接让第一个节点指向新节点,

若有,找到最后一个节点,让他指向新节点

*/

void SListPushBack(SList* s, SDataType data)

{

//找链表最后一个节点

PNode pNewNode = BuySListNode(data);

if (s->_pHead == NULL) {//链表没有节点的情况

s->_pHead = pNewNode;

}

else {

PNode pCur = s->_pHead;

while (pCur->_PNext) {

pCur = pCur->_PNext;

}

//让最后一个节点指向新节点

pCur->_PNext = pNewNode;

}

}

/*查找某个特征的节点*/

PNode SListFind(SList* s, SDataType data)

{

PNode pCur = s->_pHead;

while (pCur) {

if (pCur->_data == data) {

return pCur;

}

pCur = pCur->_PNext;

}

return NULL;

}

/*

删除给定pos位置的节点

*/

void SListErase(SList* s, PNode pos)

{

if (pos == NULL || s->_pHead == NULL) {

return;

}

if (pos== s->_pHead) {

s->_pHead = pos->_PNext;

}

else {

PNode pPrePos = s->_pHead;

while (pPrePos&&pPrePos->_PNext != pos) {

pPrePos = pPrePos->_PNext;

}

pPrePos->_PNext = pos->_PNext;

}

free(pos);

}

//获取链表有效节点的个数

int SListSize(SList* s)

{

int count = 0;

PNode pCur = s->_pHead;

while (pCur) {

count++;

pCur = pCur->_PNext;

}

return count;

}

//检测链表是否为空

int SListEmpty(SList* s)

{

if (s->_pHead == NULL)

{

return -1;

}

return 0;

}

//清空链表

void SListClear(SList* s)

{

if (s->_pHead == NULL) {

return;

}

PNode pCur = s->_pHead;

while (pCur->_PNext) {    //循环清空链表中的节点

PNode Tmp = pCur->_PNext;

free(pCur);

pCur = Tmp;

}

if (pCur) {      //清空最后一个节点

free(pCur);

pCur = NULL;

}

}

//销毁链表

void SListDestroy(SList* s)

{

if (s->_pHead == NULL) {

free(s->_pHead);

return;

}

while (s->_pHead) {

PNode Tmp = s->_pHead->_PNext;

free(s->_pHead);

s->_pHead = Tmp;

}

}

//打印链表

void SListPrint(SList* s)

{

PNode pCur = s->_pHead;

while (pCur) {

printf("%d--->", pCur->_data);

pCur = pCur->_PNext;

}

printf("\n");

}

/**********************Tests**************************************

void main()

{

SList s;

SListInit(&s);

SListPushBack(&s, 1);

SListPushBack(&s, 2);

SListPushBack(&s, 3);

printf("size=%d\n", SListSize(&s));

SListPrint(&s);

SListInsert(SListFind(&s, 2), 0);

SListPrint(&s);

SListRemove(&s, 2);

SListPrint(&s);

system("pause");

return;

}

*****************************************************************/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值