您的位置:首页 > 编程语言 > C语言/C++

单链表的基本操作C语言实现

2017-10-18 21:11 537 查看
          单链表主要有以下基本操作:头插,尾插,头删,尾删,返回结点在链表中的位置,任意位置插入值为data的结点, 删除pos位置上的结点 ,求链表中节点的个数,销毁单链表 。

      代码如下所示:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#include<stdio.h>
#include<Windows.h>

typedef int DataType;
typedef struct Node
{
DataType _data;
struct Node * _pNext;
}*pNode;
//初始化链表
void InitList(pNode* pHead)
{
assert(pHead);
*pHead = NULL;
}
//创建一个新链表节点
pNode BuyNode(DataType data)
{
pNode pNewNode = (pNode)malloc(sizeof(struct Node));
if(NULL == pNewNode)
{
assert(0);
return NULL;
}
pNewNode->_data = data;
pNewNode->_pNext = NULL;
return pNewNode;
}
//尾插
void PushBack(pNode* pHead,DataType _data)
{
assert(pHead);
if(NULL == *pHead)
{
*pHead = BuyNode(_data);
}
else
{
pNode pTailNode = *pHead;
while(pTailNode->_pNext)
{
pTailNode = pTailNode->_pNext;
}
pTailNode->_pNext = BuyNode(_data);
}
}
//尾删
void PopBack(pNode* pHead)
{
if(NULL == *pHead)
return;
else if(NULL == (*pHead)->_pNext)
{
free(*pHead);
*pHead = NULL;
}
else
{
pNode pTailNode = *pHead;
pNode pPre = NULL;
while(pTailNode->_pNext)
{
pPre = pTailNode;
pTailNode = pTailNode->_pNext;
}
pPre->_pNext = NULL;
free(pTailNode);
}
}
//打印链表
void PrintList(pNode pHead)
{
pNode pCur = pHead;
while(pCur)
{
printf("%d--->",pCur->_data);
pCur = pCur->_pNext;
}
printf("NULL\n");
}
//头插
void PoshFront(pNode* pHead,DataType data)
{
pNode pNewNode;
assert(pHead);
pNewNode = BuyNode(data);
if(NULL == pNewNode)
return;
pNewNode->_pNext = *pHead;
*pHead = pNewNode;

}
//头删
void PopFront(pNode* pHead)
{
pNode pCur = *pHead;
assert(pHead);
if(NULL == pCur)
return;
else
{
*pHead = (*pHead)->_pNext;
free(pCur);
}
}
// 返回结点在链表中的位置
pNode FindList(pNode pHead,DataType data)
{
pNode pCur = pHead;
while(pCur)
{
if(pCur->_data == data)
return pCur;
else
pCur = pCur->_pNext;
}
return NULL;
}
// 任意位置插入值为data的结点
pNode Insert(pNode pos,DataType data)
{
pNode pNewNode;
if(NULL == pos)
return NULL;
pNewNode = BuyNode(data);
if(NULL == pNewNode)
return NULL;
pNewNode->_pNext = pos->_pNext;
pos->_pNext = pNewNode;
}
// 删除pos位置上的结点
void Erase(pNode* pHead,pNode pos)
{
assert(pHead);
if(NULL == *pHead || NULL == pos)
return;
if(*pHead == pos)
PopFront(pHead);
else
{
pNode pCur = *pHead;
while(pCur)
{
if(pCur->_pNext == pos)
break;
pCur = pCur->_pNext;
}
pCur->_pNext = pos->_pNext;
free(pos);
}
}
// 销毁单链表
void DestoryList(pNode* pHead)
{
//正向销毁
pNode pCur = *pHead;
pNode pNext = NULL;
while(pCur)
{
pNext = pCur->_pNext;
free(pCur);
pCur = pNext;
}
*pHead = NULL;
}
// 求链表中节点的个数
int SizeList(pNode pHead)
{
int count = 1;
pNode pCur = pHead;
while(pCur)
{
count++;
pCur = pCur->_pNext;
}
return count;
}

     然后就可以在函数模块调用以上单链表的基本操作。这里就不再放主函数了^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单链表 c语言