链表基本操作(c语言版)

单链表基础操作(c语言版)

链表是顺序结构的一种,一个链表节点中包含下一个节点的指针,当前链表的值,根据分类,链表可以分为单链表与双链表,双链表中还存在一个指向前一个节点的指针。带头链表与不带头链表,头节点为哨兵卫不存数据仅作为标记用。带环与不带环。根据排列组合一共有八种链表。我们这里为了演示方便将选用单向不带头不带环的链表。
首先我们定义节点的结构体
typedef int DataType;//链表中所存的数据类型

typedef struct SListNode
{
	struct SListNode* next;
	DataType data;
}SListNode;
每当我们对链表进行操作时,就需要一个创建新节点的函数
SListNode* BuySListNode(DataType x)
{
	SListNode* NewNode = (SListNode*)malloc(sizeof(SListNode));
	assert(NewNode);
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}
链表初始化
void SListInit(SListNode** ppHead)
{
	*ppHead = NULL;
}
销毁链表
void SListDestory(SListNode** ppHead)
{
	free(*ppHead);
	*ppHead = NULL;
}
打印链表
void SListPrint(SListNode* pHead)
{
	SListNode* ptr = pHead;
		for (;ptr != NULL;ptr = ptr->next)
		{
			printf("%d ",ptr->data);
		}
} 
链表的尾插
void SListPushBack(SListNode** ppHead, DataType x)
{
	if (*ppHead == NULL)
	{
		*ppHead = BuySListNode(x);
	}
	else
	{
		SListNode* head=*ppHead;
		SListNode* _next = head->next;
		while (_next!= NULL)
		{
			head = _next;
			_next = _next->next;
		}
			
		_next = BuySListNode(x);
		head->next = _next;
	}
}
链表的尾删
void SListPopBack(SListNode** ppHead)
{
	if (*ppHead == NULL)
	{
		printf("该链表为空\n");
	}
	else
	{
		SListNode* last=*ppHead;
		while (last->next->next != NULL)
		{
			last = last->next;
		}
		SListDestory(&last->next);
		last->next = NULL;
	}
}
链表的头插
void SListPushFront(SListNode** ppHead, DataType x)
{
	if (*ppHead == NULL)
	{
		*ppHead = BuySListNode(x);
	}
	else
	{
		SListNode* tmp;
		tmp = BuySListNode(x);
		tmp->next = *ppHead;
		*ppHead = tmp;
	}
}
在链表中查找数据
SListNode* SListFind(SListNode* pHead, DataType x)
{
	SListNode* str=pHead;
	while (str->data != x)
	{
		str = str->next;
	}
	if (str == NULL)
	{
		printf("该链表找不到这个数\n");
	}
	else
	{
		return str;
	}
}
任意位置插入数据
void SListInsest(SListNode** ppHead, size_t pos, DataType x)
{
	SListNode* str = *ppHead;
	SListNode* tmp = NULL;
	if (pos == 1)
	{
		SListPushBack(ppHead, x);
	}
	else
	{
		int i ;
		for (i = 1;i < pos;i++)
		{
			str = str->next;
		}
		tmp = BuySListNode(x);
		tmp->next = str->next;
		str->next = tmp;
	}
}
任意位置删除
void SListErase(SListNode** ppHead, size_t pos)
{
	SListNode* str=*ppHead;
	SListNode* tmp = NULL;
	if (*ppHead == NULL)
	{
		printf("该链表为空\n");
	}
	int i;
	for (i = 1;i < pos-1;i++)
	{
		str = str->next;
	}
	tmp = str->next;
	str->next = str->next->next;
	tmp = NULL;
	SListDestory(&tmp);
}










猜你喜欢

转载自blog.csdn.net/qq9116136/article/details/80026810