用循环单链表实现循环队列,如何写出插入和删除的算法?

用循环单链表实现循环队列,如何写出插入和删除的算法?,第1张

typedef struct CircleListNode{

Datatype d       

struct CircleList *pre,*nxt       

}*CircleList,CirListNode

typedef struct

{

CircleList Head

int num

}CircleQueue

void insertFront(CircleList *L,d)

{

if(!L)return NULL

if(*L==NULL)

{

*L=(CircleList) malloc(sizeof(CirListNode))

*L->nxt=  *L->pre=*L

*L->d=d

}

else

{      

CircleList p =(CircleList) malloc(sizeof(CirListNode))

p->nxt=*L

p->pre=*L->pre

*L->pre->nxt=p

*L->pre=p

*L=p       

}

}

循环单链表是单链表的另一种形式,其结构特点链表中最后一个结点指针域不再是结束标记,而是指向整个链表的第一个结点,从而使链表形成一个环。和单链表相同,循环链表也有带头结点结构和不带头结点结构两种,带头结点的循环单链表实现插入和删除 *** 作较为方便。

无头指针有尾指针就从尾指针找起,一个一个向前找,直至找到该队列的头指针为止,此时即可知道你需要插入和删除节点的位置

有头指针的无尾指针,从队列头起,一个一个向后找,直至找到该队列的尾指针为止,此时即可知道你需要插入和删除节点的位置

插入算法:在某个位置插入节点后,此后的节点逐个后移,并且将移动后的尾指针保存下来

删除算法:将该位置后的节点逐个前移,并且移动后将删除的节点用free函数释放其占用的内存空间

先写个循环链表的实现

然后 C++ 用继承

C就组合吧,下面写个C的实现

typedef struct CircleListNode{

Datatype d

struct CircleList *pre,*nxt

}*CircleList,CirListNode

typedef struct

{

CircleList Head

int num

}CircleQueue

void insertFront(CircleList *L,d)

{

if(!L)return NULL

if(*L==NULL)

{

*L=(CircleList) malloc(sizeof(CirListNode))

*L->nxt= *L->pre=*L

*L->d=d

}

else

{

CircleList p =(CircleList) malloc(sizeof(CirListNode))

p->nxt=*L

p->pre=*L->pre

*L->pre->nxt=p

*L->pre=p

*L=p

}

}

void DeleteBack(CircleList *L)

{ CircleList r=*L->pre

if(*L->nxt =*L){ free(*L)*L=NULLreturn }

r->pre->nxt =*L

*L->pre=r->pre

free(r)

}

void InsertQueue(CircleQueue *que, Datatype d)

{

if(!que)return

insertFront(&que->Head,d)

que->num ++

}

void DeletQueue(CircleQueue *que)

{

if(que->num>0)

{

DeleteBack(&que->Head)

que->num--

}

}

void InitQueue(CircleQueue *que)

{

if(!que)return

que->Head=NULL

que->num=0

}

Datatype * GetBackData(const CircleQueue *que)

{

if(!que)return NULL

if(!que->Head)return NULL

if(que->num<=0)return NULL

return &(que->Head->pre->d)

}

void ClearQueue(CircleQueue *que)

{

if(!que)return

while(que->num>0)

{

DeletQueue(que)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/7980384.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存