// 根据情况把新结点插入到链表中,此时可以分为尾部插入、头部插入、指定位置插入。
typedef int DataType_t;
void LList *LList_InsertNode(DataType_t data, int p, LList_t *Head) // 传入想插入的位置p
{
// 1.备份新的节点并做错误处理
LList_t *new = LList_NewNode(data);
if (new == NULL)
{
perror("Calloc memory for Head is Failed");
exit(-1);
}
// 2.头部插入,P的位置为零如果为零的话就是插入到了头部
if (p == 0)
{
new->next = Head->next; // 把原本的头节点的地址传给新结点的
Head->next = new; // 再把新的结点new的地址覆盖到头结点的指针域
return;
}
// 3.找到要插入位置的前一个节点
LList_t *current = Head.; // 定义一个当前指针的位置
int currentp = 0; // 该位置为零往后遍历
while (current != NULL && currentp < p - 1) //
{
current = current->next; // 不满足循环条件地址偏移到后面的结点
currentp++;
}
// 4.如果未找到指定位置的前一个节点,则无法插入
if (current == NULL)
{
printf("Position is out of range\n");
return;
}
// 将新节点插入到指定位置
new->next = current->next; // 和头部插入的逻辑一样
current->next = new;
}