美文网首页
链式队列

链式队列

作者: qianranow | 来源:发表于2021-03-28 20:54 被阅读0次

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct Node {
        int data;
        struct Node *next;
    } LinkNode;
    
    typedef struct {
        LinkNode *front, *rear;
    } LinkQueue;
    
    // 带头结点
    int InitQueue(LinkQueue *q) {
        q->front = q->rear = (LinkNode *)malloc(sizeof(LinkNode));
        if (q->front == NULL) return -1;
        q->front->next = NULL;
        return 1;
    }
    
    // 带头结点
    int EnQueue(LinkQueue *q, int e) {
        LinkNode *s = (LinkNode *)malloc(sizeof(LinkNode));
        if (s == NULL) return -1;
        q->rear->next = s;
        q->rear = s;
        s->next = NULL;
        s->data = e;
        return 1;
    }
    
    // 带头结点
    int DeQueue(LinkQueue *q, int *e) {
        if (q->front == q->rear) return -1;
        LinkNode *p = q->front->next;
        *e = p->data;
        q->front->next = p->next;
        if (q->rear == p) {
            q->rear = q->front;
        }
        free(p);
        return 1;
    }
    
    // 不带头结点
    int InitQueue1(LinkQueue *q) {
        q->front = q->rear = NULL;
        return 1;
    }
    
    // 不带头结点
    int EnQueue1(LinkQueue *q, int e) {
        LinkNode *s = (LinkNode *)malloc(sizeof(LinkNode));
        if (s == NULL) return -1;
        s->next = NULL;
        s->data = e;
        if (q->front == NULL) {
            q->front = s;
            q->rear = s;
        } else {
            q->rear->next = s;
            q->rear = s;
        }
        return 1;
    }
    
    // 不带头结点
    int DeQueue1(LinkQueue *q, int *e) {
        if (q->front == NULL) return -1;
        LinkNode *p = q->front;
        q->front = p->next;
        *e = p->data;
        if (q->rear == p) {
            q->front = NULL;
            q->rear = NULL;
        }
        free(p);
        return 1;
    }
    
    // 带头结点
    int Empty(LinkQueue q) {
        if (q.front == q.rear) return 1;
        else return -1;
    }
    
    // 不带头结点
    int Emptyq(LinkQueue q) {
        if (q.front == NULL) return 1;
        else return -1;
    }
    
    int main() {
        LinkQueue q;
        InitQueue(&q);
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:链式队列

          本文链接:https://www.haomeiwen.com/subject/liulhltx.html