【必收藏】个人理解的最标准、最板正的单向链表

作为计算机专业的学生,见过挺多类型的链表,它们风格各异,好坏皆有。但是有的链表一看就懂,结构清晰,命名规范,有的链表就乱七八糟,啥也不是,bug一堆。

因此,本文展示博主自己手动编写的单向链表(有借鉴成分),力求清晰易懂,各个部分都努力做到了最标准最板正的形态。功能包含头尾加入和删除、特定位置的插入删除、查找、修改、打印所有。博主水平有限,如有错误之处,请大家指正!

【注】:基本上是C语言写的,含有少量C++成分。

话不多说,我是下雨不带伞,喜欢点个关注,一起来看代码。

#include <iostream>
using namespace std;

typedef int datatype;

struct SListNode
{
	datatype data;
	struct SListNode *next;
};

//打印 
void SListPrint(SListNode *phead)
{
	SListNode *cur = phead;
	while(cur!= NULL)
	{
		cout<<cur->data<<" ";
		cur = cur->next;
	}
}
	
//尾插	
void SListPushBack(SListNode **pplist, datatype x)
{
	SListNode *newnode = new SListNode();
	newnode->data = x;
	newnode->next = NULL;
	if(*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SListNode *tail = *pplist;
		while(tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}


//尾删 
void SListPopBack(SListNode **pplist)
{
	if(*pplist == NULL)
	{
		return; 
	}
	else if((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode *tail = (*pplist)->next;
		SListNode *prev = *pplist;
		while(tail->next != NULL)
		{
			tail = tail->next;
			prev = prev->next;
		}
		free(tail);
		prev->next = NULL;
	}
}

//头插
void SListPushFront(SListNode **pplist, datatype x)
{
	SListNode *newnode = new SListNode();
	newnode->data = x;
	newnode->next = NULL;
	if(*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		newnode->next = *pplist;
		*pplist = newnode;
	}
} 

//头删
void SListPopFront(SListNode **pplist)
{
	if(*pplist == NULL)
	{
		return;
	}
	else
	{
		SListNode *cur = *pplist;
		*pplist = (*pplist)->next;
		delete cur;
	}
 } 

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

//插入 
void SListInsertAfter(SListNode *pos, datatype x)
{
	//assert(pos);
	SListNode *newnode = new SListNode();
	newnode->data = x;
	newnode->next = NULL;
	newnode->next = pos->next;
	pos->next = newnode;
}

//删除
void SListEraseAfter(SListNode *pos)
{
	if(pos->next)
	{
		SListNode *next = pos->next;
		SListNode *nextnext = next->next;
		pos->next = nextnext;
		delete next;
	}
 } 

int main()
{
	SListNode* phead = NULL;
	SListPushBack(&phead,1);
	SListPushBack(&phead,2);
	SListPushBack(&phead,3);
	SListPopFront(&phead);
	SListNode *pos = SListFind(phead,2);
	pos->data = 200;
//	SListPrint(phead);
//	SListPopBack(&phead);
//	SListPushFront(&phead,5);
	SListPrint(phead);
	return 0;
}

恭喜你看完了,看到这了不点个赞吗#滑稽

有不懂的地方欢迎评论区指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值