c语言设计字符顺序栈
时间: 2023-08-05 21:07:30 浏览: 98
下面是一个简单的 C 语言实现字符顺序栈的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
bool push(Stack *s, char c) {
if (isFull(s)) {
return false;
}
s->data[++s->top] = c;
return true;
}
bool pop(Stack *s, char *c) {
if (isEmpty(s)) {
return false;
}
*c = s->data[s->top--];
return true;
}
bool getTop(Stack *s, char *c) {
if (isEmpty(s)) {
return false;
}
*c = s->data[s->top];
return true;
}
int main() {
Stack s;
initStack(&s);
push(&s, 'a');
push(&s, 'b');
push(&s, 'c');
char c;
while (pop(&s, &c)) {
printf("%c ", c);
}
printf("\n");
return 0;
}
```
该代码中定义了一个 `Stack` 结构体,其中包含一个字符数组 `data` 和一个整数 `top`,表示栈顶位置。`initStack` 函数用于初始化栈,将栈顶位置设为 -1。`isEmpty` 和 `isFull` 函数分别用于判断栈是否为空或已满。`push` 函数用于将元素入栈,如果栈已满则返回 `false`。`pop` 函数用于将栈顶元素出栈,如果栈为空则返回 `false`。`getTop` 函数用于获取栈顶元素,但不改变栈的状态。最后的 `main` 函数演示了如何使用该栈,将三个元素依次入栈并出栈输出。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)