求几个有关链表的最基本算法
发布网友
发布时间:2022-05-03 01:37
我来回答
共1个回答
热心网友
时间:2022-06-29 03:59
这个也太多了!
1.循环单链表,且含有头结点的
p = head->next;
for(len=0;p->next!=head;p=p->next)
{
len++ //长度加1
}
2.插入
Status ListInsert(DuLinkList L, int i, ElemType e)
{
DuLinkList p, s;
//i值不合法
if(i < 1 || i > ListLength(L) + 1) return ERROR;
//在L中确定第i个元素前驱的位置指针p
p = GetElemP(L, i - 1);
//p=NULL,即第i个元素的前驱不存在(设头结点为第1个元素的前驱)
if(!p) return ERROR;
//给插入的数据分配空间
s = (DuLinkList)malloc(sizeof(DuLNode));
//如果为空,分配失败
if(!s) return OVERFLOW;
//在第i-1个元素之后插入
s->data = e;
s->prior = p;
s->next = p->next;
p->next->prior = s;
p->next = s;
return OK;
}
删除
Status ListDelete(DuLinkList L,int i,ElemType *e)
{
DuLinkList p;
// i值不合法
if(i < 1) return ERROR;
// 在L中确定第i个元素的位置指针p
p = GetElemP(L, i);
// p=NULL,即第i个元素不存在
if(!p) return ERROR;
*e = p->data;
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
return OK;
}
3.带有头结点
p=head->next;
head->next =NULL;
q= head;
while(p)
{
q->next = p;
q = p;
p=p->next
}
4.带头结点
p=head->next;
head->next = head;
q = head;
while(p!=head)
{
if(head->next = head){q->next=p;q->next = head;}
else{q->next = p;}
q = p;
}
5.带头结点
p = head->next;
p->prior = NULL;
q = head;
while(p)
{
q->prior = p;
q->next = p->next;
p->next->prior = q;
p->next = q;
}