# 玩转链表（1）

## 顺序表问题及思考

1. 中间/头部的插入删除，时间复杂度为O(N)
2. 增容需要申请新空间，拷贝数据，释放旧空间。会有不小的消耗。
3. 增容一般是呈2倍的增长，势必会有一定的空间浪费。例如当前容量为100，满了以后增容到200，
我们再继续插入了5个数据，后面没有数据插入了，那么就浪费了95个数据空间。

## 打印链表节点数据

void SListPrint(SLTNode* plist)
{
SLTNode* cur = plist;
while (cur != NULL)
{
printf("%d "cur->data);
cur = cur->next;
}
printf("\n");
}

## 建立一个新的节点

{
SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
node->data = x;
node->next = NULL;
}

## 尾插

void SListPushBack(SLTNode** plist, SLTDataType x)
{
if (plist == NULL)
{
plist = newnode;
}
else
{
SLTNode* tail = plist;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}

## 头插

void SListPushFront(SLTNode** pplist, SLTDataType x)
{
newnode->next = *pplist;
*pplist = newnode;
}

## 尾删

void SListPopBack(SLTNode* plist)
{
if (*pplist == NULL)
{
return;
}
else if ((*pplist)->next == NULL)
{
free(*pplist);
*pplist = NULL;
}
else
{
SLTNode* prev = NULL;
SLTNode* tail = plist;
while (tail->next != NULL)
{
prev = tail;
tail = tail->next;
}
free(tail);
tail = NULL;
prev->next = NULL;
}
}

## 头删

void SListPopFront(SLTNode ** pplist)
{
if (*pplist == NULL)
{
return;
}
else
{
SLTNode* next = (*pplist)->next;
free(*pplist);
*pplist = next;
}
}

## 查找

void SLTNode* SListFinde(SLTNode* plist, SLTDataType x)
{
SLTNode* cur = plist;
while (cur)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
}

## 任意位置前插入

void SListInsert(SLTNode* plist, SLTNode* pos, SLTDataType x)
{
assert(pos);
if (pos == *pplist)
{
newnode->next = pos;
*pplist = newnode;
}
SLTNode* prev = NULL;
SLTNode* cur = plist;
while (cur != pos)
{
prev = cur;
cur = cur->next;
}
prev->next = newnode;
newnode->next = pos;
}

## 任意位置后插入

void SListInsertAfter(SLTNode* pos, SLTDataType x)
{
assert(pos);