单向队列
额~~~,相信各位都是巨巨这点内容就不用我介绍啦。
今天十月二十四,程序员节快乐。
(其实写这篇文章也就是为了刷一个徽章而已,Orz,太卑微啦)
队列代码实现:
#include<stdlib.h>
#include<iostream>
#include<stdio.h>
#define True 1
#define False 0
#define OK 1
#define Error 0
#define Infeasible -1
#define Overflow -2
typedef int Status;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 2
#define SElemType char
#define QElemType char
typedef struct QNode
{
QElemType data;
QNode *next;
}*QueuePtr;
using namespace std;
struct LinkQueue
{
QueuePtr front,rear; // 队头、队尾指针
};
// bo3-2.cpp 链队列(存储结构由c3-2.h定义)的基本操作(9个)
Status InitQueue(LinkQueue &Q)
{ // 构造一个空队列Q
QueuePtr q;
q=(QueuePtr)malloc(sizeof (QNode));
q->next=NULL;
Q.front=q;
Q.rear=q;
}
Status DestroyQueue(LinkQueue &Q)
{ // 销毁队列Q(无论空否均可)
while(Q.front)
{
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear;
}
Q.front=NULL;
Q.rear=NULL;
return 1;
}
Status ClearQueue(LinkQueue &Q)
{ // 将Q清为空队列
QueuePtr cn;
while(Q.front!=Q.rear)
{
cn=Q.front->next;
free(Q.front->next);
Q.front=cn;
}
if(Q.front==Q.rear)
return 1;
return 0;
}
Status QueueEmpty(LinkQueue Q)
{ // 若Q为空队列,则返回TRUE,否则返回FALSE
if(Q.rear==Q.front)
return 1;
else{
return 0;
}
}
int QueueLength(LinkQueue Q)
{ // 求队列的长度
int cnt=0;
while(Q.front!=Q.rear)
{
cnt++;
Q.front=Q.front->next;
}
return cnt;
}
Status GetHead(LinkQueue Q,QElemType &e)
{ // 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
if(Q.front==Q.rear)
{
return Error;
}
e=Q.front->next->data;
return 1;
}
Status EnQueue(LinkQueue &Q,QElemType e)
{ // 插入元素e为Q的新的队尾元素
QueuePtr temp;
temp=(QueuePtr)malloc(sizeof(QNode) );
if(!temp)exit(Overflow);///分配空间失败
temp->next=NULL;
temp->data=e;
Q.rear->next=temp;
Q.rear=temp;
return 1;
}
Status DeQueue(LinkQueue &Q,QElemType &e)
{ // 若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR
if(Q.front==Q.rear)
{
return Error;
}
QueuePtr temp=Q.front->next;
e=temp->data;
Q.front->next=temp->next;
if(Q.rear==temp)Q.rear=Q.front;
free(temp);
return 1;
}
Status QueueTraverse(LinkQueue Q,void(*vi)(QElemType))
{ // 从队头到队尾依次对队列Q中每个元素调用函数vi()。一旦vi失败,则操作失败
if(Q.front==Q.rear)
{
return 0;
}
QueuePtr cn=Q.front->next;
//vi(cn->data);
while(cn)
{
vi(cn->data);
cn=cn->next;
}
if(!cn)
{
return 1;
}
return 0;
}
void visit(QElemType i)
{
printf("%c ",i);
}
int main()
{
int i;
QElemType d;
LinkQueue q;
i=InitQueue(q);
if(i)
printf("成功地构造了一个空队列!\n");
// printf("%d",QueueEmpty(q));
printf("是否空队列?%d(1:空 0:否) \n",QueueEmpty(q));
printf("队列的长度为%d\n",QueueLength(q));
EnQueue(q,-5);
EnQueue(q,5);
EnQueue(q,10);
printf("插入3个元素(-5,5,10)后,队列的长度为%d\n",QueueLength(q));
printf("是否空队列?%d(1:空 0:否) ",QueueEmpty(q));
printf("队列的元素依次为:");
QueueTraverse(q,visit);
i=GetHead(q,d);
if(i==OK)
printf("队头元素是:%d\n",d);
DeQueue(q,d);
printf("删除了队头元素%d\n",d);
i=GetHead(q,d);
if(i==OK)
printf("新的队头元素是:%d\n",d);
ClearQueue(q);
printf("清空队列后,q.front=%u q.rear=%u q.front->next=%u\n",q.front,q.rear,q.front->next);
DestroyQueue(q);
printf("销毁队列后,q.front=%u q.rear=%u\n",q.front, q.rear);
}
总结:
代码很清楚,自我感觉各位可以直接用来交作业(如果不嫌弃的话)。
如果有错误,希望各位能不吝赐教哦。
告诫:
勿失本心。
节日快乐o(∩_∩)o。