如何用C创建一个顺序栈
时间: 2023-12-25 21:04:23 浏览: 30
以下是用C语言创建一个顺序栈的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} SeqStack;
void initStack(SeqStack *s) {
s->top = -1;
}
int isEmpty(SeqStack *s) {
return s->top == -1;
}
int isFull(SeqStack *s) {
return s->top == MAXSIZE - 1;
}
int push(SeqStack *s, int value) {
if (isFull(s)) {
printf("Stack is full.\n");
return 0;
}
s->top++;
s->data[s->top] = value;
return 1;
}
int pop(SeqStack *s, int *value) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return 0;
}
*value = s->data[s->top];
s->top--;
return 1;
}
int main() {
SeqStack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
int value;
pop(&s, &value);
printf("%d\n", value);
pop(&s, &value);
printf("%d\n", value);
pop(&s, &value);
printf("%d\n", value);
pop(&s, &value);
return 0;
}
```
这个顺序栈使用一个数组来存储数据,同时用一个整数来表示栈顶元素的位置。栈的初始化、判空、判满、入栈、出栈等操作都比较简单,需要注意的是入栈时需要先判满,出栈时需要先判空。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)