数据结构实验5

题目:假设以数组 sequ[MaxSize]存放环形队列的元素,同时 Rear 和 Len 分别指示 环形队列中队尾元素的位置和内含元素的个数。设计相应的入队和出队算法。

test.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>

#define MaxSize 5
typedef int elemtype;
typedef struct SequenQueue
{
    elemtype sequ[MaxSize];
    int Len;        //内含元素的个数
    int Rear;        //队尾元素的位置
}SequenQueue;
SequenQueue *Init_SequenQueue()
{
    SequenQueue * Q;
    Q = (SequenQueue *)malloc(sizeof(SequenQueue));
    if (Q == NULL)
    {
        printf("申请空间失败\n");
        exit(0);
    }

    if (Q != NULL)
    {
        Q->Rear = 0;
        Q->Len = 0;
    }
    return Q;
}
void entryQueue(SequenQueue *Q)
{
    int x,First;
    if (Q->Len == MaxSize)
    {
        printf("队列已满,不能入列。\n");
        return;
    }
    printf("输入x:");
    scanf("%d", &x);

    Q->sequ[Q->Rear] = x;    //入队
    Q->Rear = (Q->Rear + 1) % MaxSize;        //移动队尾指针
    Q->Len++;
    First = ((Q->Rear + MaxSize) - Q->Len + 1) % MaxSize-1;        //计算队头元素的下标
    printf("%d已入列\n",x);
    printf("尾部位置%d\n", Q->Rear);
    printf("头部位置%d\n", First);
    printf("\n");
}

int exitQueue(SequenQueue *Q)
{
    int x, First;//队头元素的下标
    if (Q->Len == 0)
    {
        printf("队列已空,不能出队\n");
        return -1;
    }
    First = ((Q->Rear + MaxSize) - Q->Len + 1) % MaxSize-1;        //计算队头元素的下标
    x = Q->sequ[First];            //获得队头元素
    Q->Len--;                    //长度减一
            First = ((Q->Rear + MaxSize) - Q->Len + 1) % MaxSize;        //计算队头元素的下标
    printf("已将%d出列\n", x);
    printf("尾部位置%d\n", Q->Rear);
    printf("头部位置%d\n", First);
    printf("\n");
    return x;
}
void menu()
{
    printf("--菜单栏--\n");
    printf("1.入列\n");
    printf("2.出列\n");
    printf("3.输出列的内容\n");
    printf("0.退出\n");
    printf("\n");
}

void Print(SequenQueue *Q)
{
    int a, First,i = 0;
    a = Q->Len;
    First = ((Q->Rear + MaxSize) - Q->Len + 1) % MaxSize-1;        //计算队头元素的下标
    printf("列内的数据元素分别为:");
    while (a != 0)
    {
        printf("%d  ", Q->sequ[(First + i) % MaxSize]);
        a--;
        i++;
    }
    printf("\n\n");
}

test.c

#include"test.h"
void main()
{
    char i;
    SequenQueue *Q;
    Q = Init_SequenQueue();
    menu();
//    scanf("%d", &i);
    i = _getch();
    while (i)
    {
        switch (i)
        {
        case '0':
            exit(0);
            break;
        case '1':
            entryQueue(Q);
            break;
        case '2':
            exitQueue(Q);
            break;
        case '3':
            Print(Q);
            break;
        default:
            printf("请输入正确的序号!\n");
            printf("\n");
            break;
        }
    //    scanf("%d", &i);
        printf("继续输入序号进行操作\n");
        i = _getch();
    }
}

 

posted @ 2017-06-01 20:20  五邑bb  阅读(1699)  评论(0编辑  收藏  举报