typedef int Item;
typedef struct node
{
Item item;
struct node * next;
}Node;
typedef struct queue
{
Node* front; /*指向队列首的指针*/
Node* rear; /*指向队列尾的指针*/
int items; /*队列中项目的个数*/
}
1.向队列尾端添加项目步骤:
1.1 创建新节点
1.2把项目复制到新节点
1.3设置节点的next指针为null,表明该节点时列表中的最后一个节点
1.4设置当前尾节点的next指针指向新的节点,从而将将新节点链接到队列中
1.5把rear指针设置为指向新节点,以便找到最后的节点
1.6项目个数加1
bool EnQueue(Item item, Queue* pq)
{
Node* pnew;
if(QuueIsFull(pq))
return false;
pnew=(Node*)malloc(sizeof(Node));
if(pnew == NULL)
{
fprintf(stderr, "Unable to allocate memory");
exit(1);
}
CopyToNode(item, pnew);
pnew->next= NULL;
if(QueueIsEmpty(pq))
pq->front = pnew;
else
pq->rear->next = pnew;
pq->rear = pnew;
pq->items++;
return ture;
}
2.向队列首端删除项目步骤:
2.1 把项目复制到一个给定的变量中
2.2释放空闲节点使用的内存
2.3重置首指针,使其指向队列的下一项
2.4如果最后一项被删除,把首尾指针重置为NULL
1.6项目个数减少1
bool DeQueue(Item* pitem, Queue* pq)
{
Node* pt;
if(QueueIsEmpty(pq))
{
return false;
}
CopyToItem(pq->front, pitem);
pt = pq->font;
pq->font = pq->front->next;
free(pt);
pq->items--;
if(pq->items == 0)
{
pq->rear =NULL;
}
reurn true;
}