作为计算机专业的学生,见过挺多类型的链表,它们风格各异,好坏皆有。但是有的链表一看就懂,结构清晰,命名规范,有的链表就乱七八糟,啥也不是,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;
}
恭喜你看完了,看到这了不点个赞吗#滑稽
有不懂的地方欢迎评论区指出!