C 队列的基本操作

//
//  main.c
//  队列
//
//  Created by 赫凯 on 2018/10/30.
//  Copyright © 2018 赫凯. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>

typedef char Elemtype;
typedef struct QNode{
    Elemtype data;
    struct QNode *next;
}QNode, *QueuePrt;

typedef struct {
    QueuePrt front, rear;
}LinkQueue;
//初始化
void initQueue(LinkQueue *q){
    q->front = q->rear = (QueuePrt)malloc(sizeof(QNode));
    if(!q->front)
        exit(0);
    q->front->next = NULL;
}
//插入一个节点
void InsertQueue(LinkQueue *q, Elemtype e){
    QueuePrt p;
    p = (QueuePrt)malloc(sizeof(QNode));
    if(p == NULL)
        exit(0);
    p->data = e;
    p->next = NULL;
    
    //插进去
    q->rear->next = p;
    q->rear = p;
}
//出队列
void DeleteQueue(LinkQueue *q, Elemtype *e){
    QueuePrt p;
    if( q->front == q->rear ){
        return;
    }
    
    p = q->front->next;
    *e = p->data;
    
    q->front->next = p->next;
    if(q->rear == p)
        q->rear = q->front;
    free(p);
}
//销毁一个队列
void DestroyQueue(LinkQueue *q){
    while (q->front) {
        q->rear = q->front->next;
        free(q->front);
        q->front = q->rear;
    }
}



int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    
    LinkQueue q;
    initQueue(&q);
    
    char c;
    scanf("%c", &c);
    while (c != '#') {
        InsertQueue(&q, c);
        scanf("%c", &c);
    }
    getchar();
    while (q.front != q.rear) {
        DeleteQueue(&q, &c);
        printf("%c",c);
    }
    
    return 0;
}

posted @ 2018-10-31 10:36  赫凯  阅读(62)  评论(0)    收藏  举报