c语言构建顺序栈类型,实现顺序栈的初始化、判满、判空、入栈、出栈、读取栈顶元素运算,基于顺序栈实现表达式或文本中括号是否匹配的检验;构建循环队列类型,实现循环队列的初始化、判满、判空、入队、出队、读取队头元素、读取队尾元素的运算,基于循环队列实现杨辉三角形N行数据的输出
时间: 2023-11-08 16:19:30 浏览: 120
#pragma once
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top; //栈顶指针
} SqStack;
//初始化顺序栈
void InitStack(SqStack* s) {
s->top = -1;
}
//判断栈是否为空
bool StackEmpty(SqStack* s) {
if (s->top == -1) {
return true;
}
return false;
}
//判断栈是否已满
bool StackFull(SqStack* s) {
if (s->top == MAXSIZE - 1) {
return true;
}
return false;
}
//入栈
bool Push(SqStack* s, char e) {
if (StackFull(s)) {
return false;
}
s->top++;
s->data[s->top] = e;
return true;
}
//出栈
bool Pop(SqStack* s, char* e) {
if (StackEmpty(s)) {
return false;
}
*e = s->data[s->top];
s->top--;
return true;
}
//读取栈顶元素
bool GetTop(SqStack* s, char* e) {
if (StackEmpty(s)) {
return false;
}
*e = s->data[s->top];
return true;
}
//括号匹配检验
bool CheckBracketMatch(char* str) {
SqStack s;
InitStack(&s);
int i = 0;
while (str[i] != '\0') {
if (str[i] == '(' || str[i] == '{' || str[i] == '[') {
Push(&s, str[i]);
}
else if (str[i] == ')' || str[i] == '}' || str[i] == ']') {
char topElem;
if (StackEmpty(&s)) {
return false;
}
Pop(&s, &topElem);
if (str[i] == ')' && topElem != '(') {
return false;
}
if (str[i] == '}' && topElem != '{') {
return false;
}
if (str[i] == ']' && topElem != '[') {
return false;
}
}
i++;
}
if (!StackEmpty(&s)) {
return false;
}
return true;
}
typedef struct {
int data[MAXSIZE];
int front; //队头指针
int rear; //队尾指针
} SqQueue;
//初始化循环队列
void InitQueue(SqQueue* q) {
q->front = 0;
q->rear = 0;
}
//判断队列是否为空
bool QueueEmpty(SqQueue* q) {
if (q->front == q->rear) {
return true;
}
return false;
}
//判断队列是否已满
bool QueueFull(SqQueue* q) {
if ((q->rear + 1) % MAXSIZE == q->front) {
return true;
}
return false;
}
//入队
bool EnQueue(SqQueue* q, int e) {
if (QueueFull(q)) {
return false;
}
q->data[q->rear] = e;
q->rear = (q->rear + 1) % MAXSIZE;
return true;
}
//出队
bool DeQueue(SqQueue* q, int* e) {
if (QueueEmpty(q)) {
return false;
}
*e = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return true;
}
//读取队头元素
bool GetHead(SqQueue* q, int* e) {
if (QueueEmpty(q)) {
return false;
}
*e = q->data[q->front];
return true;
}
//读取队尾元素
bool GetTail(SqQueue* q, int* e) {
if (QueueEmpty(q)) {
return false;
}
*e = q->data[(q->rear - 1 + MAXSIZE) % MAXSIZE];
return true;
}
//输出杨辉三角形N行数据
void PrintYangHui(int n) {
SqQueue q;
InitQueue(&q);
EnQueue(&q, 1); //第一行只有一个1
for (int i = 2; i <= n; i++) {
EnQueue(&q, 1); //每一行开头为1
int pre = 1;
for (int j = 2; j <= i - 1; j++) { //计算中间的数
int cur;
DeQueue(&q, &cur);
EnQueue(&q, cur + pre);
pre = cur;
}
EnQueue(&q, 1); //每一行结尾为1
}
//输出
while (!QueueEmpty(&q)) {
int e;
DeQueue(&q, &e);
printf("%d ", e);
}
}
阅读全文