【資料結構】迴圈佇列 C語言實現

金艦發表於2018-05-04

“Queue.h”

#include "Queue.h"
#include <stdio.h>
#include <stdlib.h>
status Queue_init(SqQueue *Q)
{
    Q->data = (char*)malloc(sizeof(char)*MAXSIZE);
    Q->front = 0;
    Q->rear = 0;
    return OK;
}

status Queue_In(SqQueue *Q,char e) //進入佇列
{
    if((Q->rear +1)%MAXSIZE ==Q->front)
    {
        printf("佇列已滿");
        return ERROR;
    }
    Q->data[Q->rear] = e;
    Q->rear =(Q->rear+1)%MAXSIZE;
    return OK;
}

char Queue_Out(SqQueue *Q)
{
    char e;
    if(Q->front == Q->rear)
    {
        printf("佇列為空");
        return ERROR;
    }
    e = Q->data[Q->front];
    Q->front = (Q->front+1)%MAXSIZE;
    return e;
}
void Print_Queue(SqQueue Q)
{
    int i=Q.front;
    printf("佇列:
");
    while(i!= Q.rear)
    {
        printf("%c",Q.data[i]);
        i = (i+1)%MAXSIZE;
    }
    printf("
");
}

int Queue_length(SqQueue Q)
{
    return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}

“main.c”

#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
#include <string.h>

int main()
{
    SqQueue Q;
    char c;
    char rec[MAXSIZE] ;
    int i;
    Queue_init(&Q);
    printf("請輸入一個字串:
");
    gets(rec);
    for(i=0;rec[i]!= `

相關文章