单链表相关操作--C语言实现

结构体的创建
typedef int DataType;
typedef struct Node
{
	struct Node* _pNext;
	DataType _data;
}Node, *PNode;

创建一个新节点
PNode BuyNode(DataType data)
{
	PNode pnew = NULL;
	pnew = (PNode)malloc(sizeof(Node));
	if (NULL == pnew)
	{
		printf("malloc开辟空间失败!!");
	}
	else
	{
		pnew->_data = data;
		pnew->_pNext = NULL;
	}
	return pnew;
}

链表的插入
1.在链表的尾部插入一个新节点
void SListPushBack(PNode* pHead, DataType data)
{
	if (NULL == *pHead)
	{
		*pHead = BuyNode(data);
	}
	else
	{
		PNode pcur = *pHead;
		while (pcur->_pNext)
		{
			pcur = pcur->_pNext;
		}
		pcur->_pNext = BuyNode(data);
	}
}

2.在链表的头部插入一个新节点

void SListPushFront(PNode* pHead, DataType data)
{
	assert(pHead);
	if (!(*pHead))
	{
		*pHead = BuyNode(data);
	}
	else
	{
		PNode pcur = *pHead;
		*pHead = BuyNode(data);
		(*pHead)->_pNext = pcur;
	}
}

3.在链表的指定位置后插入一个新节点

void SListInsert(PNode* pHead, PNode pos, DataType data)
{
	assert(pHead);
	assert(pos);
	PNode pcur = pos->_pNext;
	pos->_pNext = BuyNode(data);
	free(pcur);
	pcur = NULL;
}

链表的删除
1.在链表的尾部删除一个节点
void SListPopBack(PNode* pHead)
{
	assert(pHead);
	if (NULL == *pHead)
	{
		return;
	}
	else if (!(*pHead)->_data)
	{
		PNode pcur = *pHead;
		pHead = NULL;
		free(pcur);
		pcur = NULL;
	}
	else
	{
		PNode pcur = *pHead;
		while (pcur->_pNext)
		{
			pcur = pcur->_pNext;
		}
		PNode pret = pcur;
		pcur = NULL;
		free(pret);
		pret = NULL;
	}
}

2.在链表的头部删除一个节点
void SListPopFront(PNode* pHead)
{
	if (!(*pHead))
	{
		return;
	}
	else if(!((*pHead)->_pNext))
	{
			PNode pcur = *pHead;
			*pHead = NULL;
			free(pcur);
			pcur = NULL;
	}
	else
	{
		PNode pcur = (*pHead)->_pNext;
		PNode pret = *pHead;
		*pHead = pcur;
		free(pret);
		pret = NULL;
	}
}

3.删除指定位置的节点

void SListErase(PNode* pHead, PNode pos)
{
	assert(pHead);
	assert(pos);
	if (*pHead == pos)
	{
		*pHead = pos->_pNext;
	}
	else
	{
		PNode pcur = *pHead;
		PNode pret = (*pHead)->_pNext;
		while (pret != pos)
		{
			pcur = pcur->_pNext;
			pret = pret->_pNext;
		}
		pcur->_pNext = pos->_pNext;
	}
	free(pos);
}

求链表中节点的个数
int SListSize(PNode pHead)
{
 int count = 0;
 PNode pcur = pHead;
 while (pcur)
 {
  count++;
  pcur = pcur->_pNext;
 }
 return count;
}

获取链表尾部的地址
PNode SListBack(PNode pHead)
{
	PNode pcur = NULL;
	pcur = pHead;
	while (pcur&&pcur->_pNext)
	{
		pcur = pcur->_pNext;
	}
	return pcur;
}
销毁链表
void SListDestroy(PNode* pHead)
{
	assert(pHead);
	PNode pcur = *pHead;
	while (pcur)
	{
		PNode pret = NULL;
		pret = pcur;
		pcur = pcur->_pNext;
		free(pret);
	}
	*pHead = NULL;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值