c语言实现元素1,2,3,4,5的进栈,出栈次序为2,1,5,4,3
时间: 2023-09-30 15:05:25 浏览: 53
以下是使用 C 语言实现栈的代码,实现元素1,2,3,4,5的进栈,出栈次序为2,1,5,4,3:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int x) {
if (is_full(s)) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
int main() {
Stack s;
init(&s);
// 进栈1,2,3,4,5
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
push(&s, 5);
// 出栈2,1,5,4,3
printf("%d ", pop(&s)); // 2
printf("%d ", pop(&s)); // 1
printf("%d ", pop(&s)); // 5
printf("%d ", pop(&s)); // 4
printf("%d ", pop(&s)); // 3
return 0;
}
```
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)