隊列c語言實現

利用c語言實現鏈隊列及相關操作

#include <stdio.h>
#include <stdlib.h>
#define ElemType int

typedef struct node
{
    ElemType data;
    struct node * next;
}quenode,*quenlist;

struct quefr
{
    quenode *front, *rear;
};

void creat(struct quefr *q)
{
    quenode *h;
    h = (quenlist)malloc(sizeof(quenode));
    h->next = NULL;
    q->front = h;
    q->rear = h;
};

void enqueue(struct quefr *q, ElemType x)  /* 自定義函數,元素x入隊 */
{
    quenode *s;
    s = (quenode*)malloc(sizeof(quenode));
    s->data = x;
    s->next = NULL;
    q->rear->next = s;
    q->rear = s; /*隊尾指針*/
}

ElemType dequenue(struct quefr *q) /* 自定義函數實現元素出隊 */
{
    quenode *p;
    ElemType x;
    p = (quenode*)malloc(sizeof(quenode));

    if(q->front == q->rear)
    {
        printf("Quenue is NULL.\n");
        exit(1);
    }

    else
    {
        p=q->front->next;
        q->front->next = p->next;
        if(p->next == NULL)
            q->front = q->rear;
        x = p->data;
        free(p);
    }
    return x;
}

void display(struct quefr* dp)
{
    quenode* p;
    if(dp->front == dp->rear)
    {
        printf("queue is NULL!\n");
        exit(1);
    }
    p = dp->front->next; /* front is a null head node */
    while(p != NULL)
    {
        printf("data = %d\n", p->data);
        p = p->next;
    }printf("end!");
}

int main()
{
    struct quefr *que;
    int n,i,x,sel;
    void display();
    void creat();
    void enqueue();
    ElemType dequenue();

    do
    {
        printf("\n\n");
        printf("1 create queue       \n");
        printf("2 enqueue            \n");
        printf("3 dequeue            \n");
        printf("4 display            \n");
        printf("5 exit               \n");
        printf("-----------------------\n");
        printf("please chose (1 2 3 4 5):\n");
        scanf("%d",&sel);
        switch(sel)
        {
        case 1:
            {
                que = (struct quefr*)malloc(sizeof(struct quefr)); /*storage allocation*/
                creat(que);
                printf("please input the number of element which do you want to creat:\n");
                scanf("%d",&n);
                for(int i=0; i<n; i++)
                {
                    scanf("%d", &x); /*輸入元素*/
                    enqueue(que,x);
                }
                break;
            }
        case 2:
            {
                printf("please input the element:\n");
                scanf("%d", &x);
                enqueue(que,x);
                break;
            }
        case 3:
            {
                printf("x = %d\n", dequenue(que));
                break;
            }
        case 4:
            {
                display(que);
                break;
            }
        case 5:
            exit(0);
        }
    }while(sel <= 4);
    return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章