10.3

时间:2021-10-03
本文章向大家介绍10.3,主要包括10.3使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天用队列实现了回文,在编写过程中,对于数组的初始化问题,未初始化的数组会存在数组内存无法使用的情况,所以,对于定义的数组以及变量一定要在定义时进行初始化。、

代码如下:

#include<stdio.h>
#include <malloc.h>
#pragma warning(suppress : 4996)
#define MAXQSIZE 100 // 最大队列长度
#define OK 1
#define ERROR 0
struct SqQueue {
char* base;// 初始化的动态分配存储空间  
int rear;// 队尾指针,指向队尾元素的后一个元素
int front; // 队头指针,指向队头元素 
};
int InitQueue(SqQueue& Q) {// 构造一个空队列 Q
Q.base = (char*)malloc(MAXQSIZE * sizeof(char)); // 为循环队列分配存储空间
if (!Q.base) return 0;// 存储分配失败
Q.front = Q.rear = 0;
return OK;
}
int QueueLength(SqQueue Q) {// 返回队列Q中元素个数,即队列的长度
return ((Q.rear - Q.front + MAXQSIZE) % MAXQSIZE);
}
char EnQueue(SqQueue& Q, char e) {// 插入元素 e 为新的队列尾元素
if ((Q.rear + 1) % MAXQSIZE == Q.front)return ERROR; // 队列满
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return e;
}
int DeQueue(SqQueue& Q, char& e) {// 若队列不空,则删除当前队列Q中的头元素,用 e 返回其值,并返回OK
if (Q.front == Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}

int main() {
SqQueue sq_N;
int n = 0;
char ch_str[100] = {'0'};
char ch_s[100] = {'0'};
char ch_n;
InitQueue(sq_N);
for (int i = 0;; i++) {
ch_n = getchar();

if (ch_n == ' ') {
i--;
}
else if (ch_n == '\n') break;
else {
ch_s[i]= EnQueue(sq_N, ch_n);

}
if (ch_n == '/n') break;
}
n = QueueLength(sq_N);
for (int i = 0; i < n; i++) {
DeQueue(sq_N, ch_str[n-i-1]);
}
int flag = 1;
for (int i = 0; i < n; i++) {
if (ch_str[i] != ch_s[i]) {
flag = 0;
break;
}
}
if (flag == 1) {
printf("该字符串是回文字符串");
}
else printf("该字符串不是回文字符串");
}

原文地址:https://www.cnblogs.com/crimsonyu/p/15365188.html