【数据结构与算法实验】队列实现缓冲输入

实验目的: 

在代码实践中熟悉队列这一重要数据结构,提高项目规划能力,提高写代码熟练度,了解掌握getch()函数。

预期效果:

输入非回车或退格字符后,显示"等待输入中...",并将输入字符缓存

输入退格删除上一次输入的字符

输入回车打印缓冲区字符与缓冲区字符个数

实验思路:

在缓冲循环中使用getch()读入字符,读入回车则结束缓冲循环,读入退格则执行退格函数,读入其他字符则将其加入缓冲队列。

实验代码:

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

/* 队列实现 */
#define MAXSIZE 100
#define ElementType char
struct QNode{
    ElementType Data[MAXSIZE];
    int Front,Rear;
    int Size;
};
typedef struct QNode *Queue;
Queue createQueue(int Size){
    if(Size<=MAXSIZE && Size>0){
        Queue pQ;
        pQ = (Queue)malloc(sizeof(struct QNode));
        pQ->Front = 0;
        pQ->Rear = 0;
        pQ->Size = Size;

        return pQ;
    }
    else{
        puts("Error! Invalid size input when creating a new queue.");
        return NULL;
    }
}
int isFull(Queue Q){
    return (Q->Front == (Q->Rear+1)%Q->Size);
}
int isEmpty(Queue Q){
    return (Q->Front == Q->Rear);
}
void Enqueue(Queue Q, ElementType X){
    if(!isFull(Q)){
        Q->Rear = (Q->Rear+1)%Q->Size;
        Q->Data[Q->Rear] = X;
    }
    else{puts("Error! The queue is full now.");}
}
ElementType Dequeue(Queue Q){
    if(!isEmpty(Q)){
        Q->Front = (Q->Front+1)%Q->Size;
        return Q->Data[Q->Front];
    }
    else{puts("Error! The queue is empty now."); return 0;}
}
/* 队列实现 完 */

/* 主程序 */

// 退格实现
int DeleteLast(Queue Q) {
	if(!isEmpty(Q)) {
		Q->Rear = Q->Rear-1;
		return 1;
	}
	else{puts("Error! The queue is empty now."); return 0;}
}

int main() {
    // 创建缓冲队列
    Queue bufferedQueue = createQueue(50);
    // 临时变量初始化
    char currentChar;
    int waiting = 1;
    int charCount = 0;

    // 缓冲循环
    while (waiting) {
        puts("等待输入中...");
        currentChar = getch();
        // 读入回车则结束缓冲循环
        if (currentChar==13) {
            waiting = 0;
        }
        // 读入退格执行退格函数
        else if (currentChar==8) {
            if (DeleteLast(bufferedQueue)) {
            	charCount--;
			}
        }
        // 读入其他字符,将其入队 
        else {
            charCount++;
            Enqueue(bufferedQueue,currentChar);
        }
    }

    // 输出缓冲区
    printf("缓冲区:");
    while (!isEmpty(bufferedQueue)) {
        printf("%c",Dequeue(bufferedQueue));
    }
    printf("\n共%d个字符(包含空格)\n",charCount);

    getchar();
    return 0;

}

测试结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值