//在第i个位置插入元素e(带头结点的链表)
bool ListInsert(LinkList &L, int i, ElemType e)//后插法
{
if (i < 1)
return false;
/******不带头结点时需要加上这段***********/
//if (i == 1)
//{
// LNode *s =(LNode *)malloc(sizeof(LNode));
// s->data = e;
// s->next = L->next;
// L = s;
// return true;
//}
LNode *p;//指针p指向当前扫描到的结点
int j = 0;//当前p指向的是第几个结点
p = L;//L指向头结点,头结点是第0个结点(不存数据)
while (p != NULL && j < i - 1)//找到第i-1个结点
{
p = p->next;
j++;
}
if (p == NULL)//i值不合法
return false;
LNode * s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
//在p结点之前插入结点s
bool InsertPriorNode(LNode *p, LNode *s)
{
if (p == NULL || s == NULL)
return false;
s->next = p->next;
p->next = s;
ElemType tmp = s->data;
s->data = p->data;
p->data = tmp;
return true;
}
时间复杂度均为(n)和O(1)
//删除第i个结点(带头结点)
bool ListDelete(LinkList &L, int i, ElemType &e)
{
if (i < 1)
return false;
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
return false;
LNode *q = p->next;
e = q->data;
p->next = q->next;
free(q);
return true;
}
//删除指定结点
bool DeleteNode(LNode *p)
{
if (p == NULL)
return false;
LNode *q = p->next;//令q指向p的后继结点
p->data = q->data;//交换数据
p->next = q->next;
free(q);
return true;
}