有关顺序队和链队的创建,入队,出队,获取头结点数据,获取队长,判断队列是否为空,遍历队等操作
顺序队:
#includeusing namespace std; #define MAXSIZE 200000 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int ElemType; typedef int Status; typedef int TElemType; typedef int SElemType; typedef int QElemType; typedef struct{ QElemType *base; int front; int tail; }SqQueue;//不是指针类型 引用时用. 而不是-> Status InitQueue(SqQueue &Q){ Q.base=(QElemType *)malloc(MAXSIZE*sizeof(QElemType)); if(!Q.base) exit(OVERFLOW); Q.front=Q.tail=0; return OK; } int QueueLength(SqQueue Q){ return (Q.tail-Q.front+MAXSIZE)%MAXSIZE; } Status EnQueue(SqQueue &Q,QElemType e){//循环队列 if((Q.tail+1)%MAXSIZE==Q.front) return ERROR;//空出一个空间去判断是否满了 Q.base[Q.tail]=e; Q.tail=(Q.tail+1)%MAXSIZE; return OK; } Status DeQueue(SqQueue &Q,QElemType &e){ if(Q.front==Q.tail) return ERROR; e=Q.base[Q.front]; Q.front=(Q.front+1)%MAXSIZE; return OK; } SElemType GetHead(SqQueue Q,QElemType &e){ if(Q.front!=Q.tail){ e=Q.base[Q.front]; return OK; } return ERROR; } Status QueueTravel(SqQueue Q){ int p=Q.front; while(p!=Q.tail){ cout< 链队:
#includeusing namespace std; #define MAXSIZE 200000 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int ElemType; typedef int Status; typedef int TElemType; typedef int SElemType; typedef int QElemType; typedef struct Qnode{ QElemType data; struct Qnode *next; }Qnode,*QueuePtr; typedef struct{ QueuePtr front; QueuePtr tail; }linkQueue; Status InitQueue(linkQueue &Q){ Q.front=Q.tail=(Qnode *)malloc(sizeof(Qnode)); if(!Q.front) exit(OVERFLOW); Q.front->next=NULL; return OK; } Status DestroyQueue(linkQueue &Q){ Qnode *p; p=(Qnode *)malloc(sizeof(Qnode)); while(Q.front){ p=Q.front->next; free(Q.front); Q.front=p; } return OK; } Status EnQueue(linkQueue &Q,QElemType e){ Qnode *p; p=(Qnode *)malloc(sizeof(Qnode)); if(!p) exit(OVERFLOW); p->data=e;p->next=NULL;//首先要处理好插入节点 Q.tail->next=p;//然后再把节点插入 Q.tail=p;//最后更新尾结点 return OK; } Status DeQueue(linkQueue &Q,QElemType &e){ Qnode *p; p=(Qnode *)malloc(sizeof(Qnode)); if(Q.front==Q.tail) return ERROR; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.tail==p) Q.tail=Q.front;//如果删除的这个节点是尾结点了,那么我需要更新尾结点为头结点 free(p); return OK; } Status GetHead(linkQueue &Q,QElemType &e){ if(Q.front==Q.tail) return ERROR; e=Q.front->next->data; return OK; } Status QueueEmpty(linkQueue Q){ if(Q.front==Q.tail) return TRUE; return FALSE; } int QueueLength(linkQueue Q){ Qnode *p; p=(Qnode *)malloc(sizeof(Qnode)); if(!p) exit(OVERFLOW); p=Q.front; int i=0; while(p->next&&p!=Q.tail){ i++; p=p->next; } cout<<"队列中的元素个数为:"<next; while(p){ cout< data< next; } cout<<"----------------------"<



