分享单链表的代码实现
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int SLTDataType;
//单链表结点
struct SListNode
{
SLTDataType _data;
struct SListNode* _next;
};
typedef struct SListNode SLTNode;
void SListPrint(SLTNode* phead)
{
SLTNode* cur = phead;
while (cur != NULL)
{
printf("%d->", cur->_data);
cur = cur->_next;
}
printf("NULL\n");
}
//申请新结点,因多次使用,封装成函数
SLTNode* BuySListNode(SLTDataType x)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
assert(newnode);
newnode->_data = x;
newnode->_next = NULL;
}
void SListPushBack(SLTNode** pphead, SLTDataType x)
{
SLTNode* newnode = BuySListNode(x);
if (*pphead == NULL)//链表为空,无法找尾结点,直接将newnode给头指针
{
*pphead = newnode;//头指针改变,所以传了二级指针
}
else
{
//找尾结点
SLTNode* tail = *pphead;
while (tail->_next != NULL)
{
tail = tail->_next;
}
tail->_next = newnode;
}
}
void SListPushFront(SLTNode** pphead, SLTDataType x)
{
SLTNode* newnode = BuySListNode(x);
newnode->_next = *pphead;
*pphead = newnode;
}
void SListPopFront(SLTNode** pphead)
{
assert(*pphead);
assert(pphead);
//保存第一个结点的下一个位置
SLTNode* newHead = (*pphead)->_next;
free(*pphead);
*pphead = newHead;
}
void SListPopBack(SLTNode** pphead)
{
assert(pphead);
assert(*pphead);
if ((*pphead)->_next == NULL)
{
free(*pphead);
*pphead = NULL;
}
else
{
SLTNode* tail = *pphead;
//保存尾结点的前一个位置,防止删除尾结点后,新的尾结点的下一位置是野指针
SLTNode* tailPrev = NULL;
while (tail->_next != NULL)
{
tailPrev = tail;
tail = tail->_next;
}
free(tail);
tailPrev->_next = NULL;
}
}
void SListDestory(SLTNode** pphead)
{
assert(pphead);
assert(*pphead);
SLTNode* cur = *pphead;
while (cur != NULL)
{
SLTNode* curNext = cur->_next;
free(cur);
cur = curNext;
}
*pphead = NULL;
}
SLTNode* SListFind(SLTNode* phead, SLTDataType x)
{
SLTNode* cur = phead;
while (cur != NULL)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->_next;
}
}
//在pos位置之后插入x值,如在pos之前插入需要找前一个位置,效率低
void SListInsertAfter(SLTNode* pos, SLTDataType x)
{
SLTNode* newnode = BuySListNode(x);
//保存pos的下一个位置
SLTNode* posNext = pos->_next;
pos->_next = newnode;
newnode->_next = posNext;
}
//删除pos位置后的值
void SListEraseAfter(SLTNode* pos)
{
assert(pos->_next != NULL);
SLTNode* del = pos->_next;
SLTNode* delNext = del->_next;
free(del);
pos->_next = delNext;
}