1.带头结点按位插入(指定结点后插)
//带头结点按位序插入
bool ListInsert(LinkList &L, int i, int e) {
if (i < 1)
return false;
LNode *p;//指针p指向扫描到的结点
int j = 0;//当前p指向的第几个结点
p = L;//L指向头结点,头结点是第0个结点(不存数据)
while (p != NULL && j < i - 1) {//循环找到第i-1个结点
p = p->next;
j++;
}
return InsertNextNode(p, e);
}
//指定结点后插
bool InsertNextNode(LNode *p, int e)
{
if (p = NULL)
return false;
LNode * s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
return false;
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
2.不带头节点按位插入(指定结点后插)
bool ListInsert_no(LinkList &L, int i, int e) {
if (i < 1)
return false;
if (i == 1){
LNode* t = (LNode*)malloc(sizeof(LNode));
t->data = e;
t->next = L;
L = t;//头指针指向新的结点t
return true;
}
LNode *p;
int j = 1;
p = L;//p指向第一个结点
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
return InsertNextNode(p, e);
}
//指定结点后插
bool InsertNextNode(LNode *p, int e)
{
if (p = NULL)
return false;
LNode * s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
return false;
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
3.指定结点前插
//指定结点前插
bool InsertPriorNode(LNode *p, int e) {
if (p == NULL)
return false;
LNode * s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
return false;
s->next = p->next;
p->next = s;//新节点连接到s中
s->data = p->data;//将p中的元素复制到s中
p->data = e;//p中元素覆盖为e
}
//指定结点前插
bool InsertPriorNode(LNode *p, LNode*s) {
if (p == NULL||s==NULL)
return false;
s->next = p->next;
p->next = s;
int temp= p->data;
p->data = s->data;
s->data = temp;
return true;
}
4.指定结点后插
bool InsertNextNode(LNode *p, int e)
{
if (p = NULL)
return false;
LNode * s = (LNode*)malloc(sizeof(LNode));
if (s == NULL)
return false;
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
总结思维导图: