带头结点的循环链表表示队列的初始化、入队列和出队列的算法

来源:互联网 发布:2017天猫茶叶销售数据 编辑:程序博客网 时间:2024/06/06 19:13
假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点(注意不设头指针),试编写相应的队列初始化、入队列和出队列的算法。
带头结点循环链队列CLQueue的类型为以下LinkList类型:
[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. typedef struct LNode{  
  2.     ElemType data;  
  3.     struct LNode *next;  
  4. } LNode, *LinkList;  
  5. typedef LinkList CLQueue;  

实现函数如下:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Status InitCLQueue(CLQueue &rear)//队列初始化  
  2. {   
  3.    rear = (CLQueue)malloc(sizeof(LNode));  
  4.    if(!rear) return FALSE;  
  5.    rear -> next = rear;  
  6.    return TRUE;     
  7. }  
  8.   
  9. Status EnCLQueue(CLQueue &rear, ElemType x)//入队列  
  10. {   
  11.     CLQueue head,p;  
  12.     head = rear -> next;  
  13.     p = (CLQueue)malloc(sizeof(LNode));  
  14.     if(!p)return FALSE;    //储存分配失败  
  15.     p -> data = x;  
  16.     p -> next = head;  
  17.     rear -> next = p;     //把拥有元素e的新节点p赋值给原队尾的后继  
  18.     rear = p;             //将当前的p设置为队尾节点  
  19.     return TRUE;  
  20. }  
  21.   
  22. Status DeCLQueue(CLQueue &rear, ElemType &x)//出队列  
  23. {   
  24.     CLQueue head,p;  
  25.     head = rear -> next;  
  26.     if(head == rear)return FALSE;  
  27.     p = head -> next;     //将欲删除的队头结点暂存给p  
  28.     x = p -> data;        //将欲删除的队头结点的值赋给x  
  29.     head -> next = p -> next;//将原队头结点的后继p->next赋值给头结点后继  
  30.     free(p);  
  31.     return TRUE;  
  32. }  
0 0
原创粉丝点击