链队
初始化链队
#define ElemType int typedef struct QueueNode { ElemType data; struct QueueNode *next; }QueueNode; typedef struct LinkQueue { QueueNode *front; QueueNode *tail; }LinkQueue; void InitQueue(LinkQueue *Q) { QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode)); assert(s!=NULL); Q->front = Q->tail = s; Q->tail->next = NULL; } |
入队
void EnQueue(LinkQueue *Q,ElemType x) { QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode)); assert(s!=NULL); s->data = x; s->next = NULL; Q->tail->next = s; Q->tail = s; } |
得到头元素
void GetHead(LinkQueue *Q,ElemType *v) { if(Q->front == Q->tail) return; QueueNode *p = Q->front->next; *v = p->data; } |
出队
void DeQueue(LinkQueue *Q) { if(Q->front == Q->tail) { printf("╤сапря©у\n"); } QueueNode *q = Q->front->next; Q->front->next = q->next; if(q == Q->tail) { Q->tail = Q->front; } free(q); } |
获得长度
int Length(LinkQueue *Q) { int len = 0; QueueNode *p = Q->front->next; while(p!=NULL) { len++; p=p->next; } return len; } |
清除摧毁队
void clear(LinkQueue *Q) { if(Q->front == Q->tail) { return; } QueueNode *p = Q->front->next; while(p!=NULL) { Q->front->next = p->next; free(p); p = Q->front->next; } Q->tail = Q->front; } void destroyQueue(LinkQueue *Q) { clear(Q); free(Q->front); Q->front = Q->tail = NULL; } |
展示队
void ShowQueue(LinkQueue *Q) { QueueNode *p = Q->front->next; while(p!=NULL) { printf("%d",p->data); p=p->next; } printf("<:tail\n"); } |
主函数
int main() { LinkQueue q; InitQueue(&q); int v; for(int i=1;i<=10;i++) { EnQueue(&q,i); } ShowQueue(&q); DeQueue(&q); DeQueue(&q); ShowQueue(&q); GetHead(&q,&v); printf("first:%d\n",v); printf("length is %d\n",Length(&q)); clear(&q); EnQueue(&q,3); ShowQueue(&q); return 0; } |