欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 【数据结构】单链表

【数据结构】单链表

2025/2/26 1:22:53 来源:https://blog.csdn.net/weixin_73483158/article/details/139607507  浏览:    关键词:【数据结构】单链表

        c语言,带头不循环单链表。

SList.h

#pragma once#include<stddef.h>//NULL
#include<stdlib.h>//free
#include<assert.h>//asserttypedef int SLTDataType;typedef struct SLTNode
{SLTDataType data;struct SList* pnext;
}SLTNode;SLTNode* SLTInit();void SLTPushFront(SLTNode* phead, SLTDataType x);void SLTPushBack(SLTNode* phead, SLTDataType x);
SLTDataType SLTPopBack(SLTNode* phead);SLTDataType SLTPopFront(SLTNode* phead);

SList.c

#include "SList.h"static SLTNode* BuySLTNode(SLTDataType x)
{SLTNode* pnewNode = (SLTNode*)malloc(sizeof(SLTNode));if (NULL == pnewNode){perror("malloc failed");exit(-1);}pnewNode->data = x;pnewNode->pnext = NULL;return pnewNode;
}SLTNode* SLTInit()
{return BuySLTNode(0);
}void SLTPushFront(SLTNode* phead, SLTDataType x)
{SLTNode* pnewNode = BuySLTNode(x);pnewNode->pnext = phead->pnext;phead->pnext = pnewNode;
}void SLTPushBack(SLTNode* phead, SLTDataType x)
{while (phead->pnext)phead = phead->pnext;SLTNode* pnewNode = BuySLTNode(x);phead->pnext = pnewNode;
}SLTDataType SLTPopBack(SLTNode* phead)
{assert(phead->pnext);SLTNode* pDel = phead->pnext;while (pDel->pnext){phead = phead->pnext;//找最后一个的前一个pDel = pDel->pnext;//找最后一个}SLTDataType ret = pDel->data;phead->pnext = NULL;free(pDel);return ret;
}SLTDataType SLTPopFront(SLTNode* phead)
{assert(phead->pnext);SLTNode* pDel = phead->pnext;SLTDataType ret = pDel->data;phead->pnext = pDel->pnext;free(pDel);return ret;
}

test.c

#include<stdio.h>
#include"SList.h"static void print(SLTNode* phead)
{phead = phead->pnext;while (phead){printf("%d->", phead->data);phead = phead->pnext;}printf("NULL\n");
}void test1()
{SLTDataType ret = 0;SLTNode* plist1 = SLTInit(); print(plist1);SLTPushFront(plist1, 1); print(plist1);SLTPushFront(plist1, 2); print(plist1);SLTPushFront(plist1, 3); print(plist1);SLTPushFront(plist1, 4); print(plist1);SLTPushBack(plist1, 111); print(plist1);SLTPushBack(plist1, 112); print(plist1); ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopBack(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);ret = SLTPopFront(plist1); print(plist1); printf("return = %d\n", ret);
}int main()
{test1();return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词