用c语言回答上述问题
时间: 2024-10-18 14:14:09 浏览: 13
当然,这里是用C语言实现上述栈操作函数的完整版本:
```c
#include <stdio.h>
#include <stdbool.h> // 引入bool类型用于布尔判断
// 定义栈结构体和相关的辅助函数
typedef struct {
char data[MAXSIZE];
int top;
} StackR;
typedef struct {
int data[MAXSIZE];
int top;
} StackD;
// 初始化栈
void InitStackR(StackR *S) {
S-1;
}
void InitStackD(StackD *S) {
S->top = -1;
}
// 判断栈是否为空
bool IsEmptyR(const StackR *S) {
return S->top == -1;
}
bool IsEmptyD(const StackD *S) {
return S->top == -1;
}
// 入栈
void PushR(StackR *S, char e) {
if (S->top < MAXSIZE - 1) {
S->data[++S->top] = e;
} else {
printf("Error: Stack overflow.\n");
}
}
void PushD(StackD *S, int e) {
if (S->top < MAXSIZE - 1) {
S->data[++S->top] = e;
} else {
printf("Error: Stack overflow.\n");
}
}
// 出栈
char PopR(StackR *S, char *e) {
if (IsEmptyR(S)) {
printf("Error: Stack is empty.\n");
*e = '\0';
return '\0';
} else {
*e = S->data[S->top];
S->top--;
return *e;
}
}
int PopD(StackD *S, int *e) {
if (IsEmptyD(S)) {
printf("Error: Stack is empty.\n");
*e = -1;
return -1;
} else {
*e = S->data[S->top];
S->top--;
return *e;
}
}
// 取栈顶元素但不移除
char GetTopR(const StackR *S) {
if (!IsEmptyR(S)) {
return S->data[S->top];
} else {
return '\0';
}
}
int GetTopD(const StackD *S) {
if (!IsEmptyD(S)) {
return S->data[S->top];
} else {
return -1;
}
}
```
阅读全文