单链表的代码实现

单链表的链式结构代码实现


typedef int SLTDateType;
typedef struct SListNode
{
	SLTDateType data;
	struct SListNode* next;
}SListNode;

 
// 动态申请一个节点,创建指针,开辟空间
SListNode* BuySListNode(SLTDateType x)
{
	SListNode* node = (SListNode*)malloc(sizeof(SListNode));
	node->data = x;
	node->next = NULL;
}

// 单链表打印
void SListPrint(SListNode* plist)
{
	assert(plist);
	SListNode* cur = plist;
	while(cur)
	{
		printf("%d->",cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}


// 单链表尾插
void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);//创建一个新节点
	if(*pplist == NULL)//1链表为空
	{
		*pplist = newnode;
	}
	else//先找尾结点再插入
	{
		SListNode* tail = *pplist;
		while(tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}	
}

// 单链表的头插
void SListPushFront(SListNode** pplist, SLTDateType x)//会改变指针的指向,所以传二级指针
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	if(*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		newnode->next = *pplist;
		*pplist = newnode;
	}
}

// 单链表的尾删
void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	//两种情况,一种是一个节点,另一种是两个节点及其以上
	if((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* tail = *pplist;
		while(tail->next-next)//找到尾结点的上一个节点
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}


// 单链表头删
void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	//两种情况,1只有一个节点,2两个节点及其以上
	if((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* cur = (*pplist)->next;
		free(*pplist);
		*pplist = cur;
	}
}


// 单链表查找
SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	assert(plist);
	SListNode* cur = plist;
	while(cur)
	{
		if(cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;	
}


// 单链表在pos位置之后插入x
void SListInsertAfter(SListNode* pos, SLTDateType x)
{	
	assert(pos);
	SListNode* cur = pos->next;
	SListNode* newnode = BuySListNode(x);
	pos->next = newnode;
	newnode->next = cur;
	
}


// 单链表删除pos位置之后的值
void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);
	SListNode* cur = pos->next->next;
	free(pos->next);
	pos->next = cur;
}


// 单链表的销毁
void SListDestroy(SList* plist)
{
	assert(plist);
	SListNode* cur = plist;
	while(cur)
	{
		SListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	plist = NULL;
}

版权声明:本文为weixin_62521454原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_62521454/article/details/128792899