使用C语言编写代码,实现栈的基本操作,主要包括栈的创建、压栈和弹栈等操作
时间: 2024-05-09 20:16:58 浏览: 86
好的,我可以回答这个问题。栈是一种数据结构,具有先进后出的特点。以下是使用C语言实现栈的基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct Stack{
int data[MAXSIZE];
int top;
} Stack;
void push(Stack* s, int item) {
if(s->top == MAXSIZE - 1) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = item;
}
int pop(Stack* s) {
int item;
if(s->top == -1) {
printf("Stack is empty.\n");
return -1;
}
item = s->data[s->top];
s->top--;
return item;
}
int main() {
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
push(s, 10);
push(s, 20);
push(s, 30);
printf("pop: %d\n", pop(s));
printf("pop: %d\n", pop(s));
printf("pop: %d\n", pop(s));
printf("pop: %d\n", pop(s));
free(s);
return 0;
}
```
在这个实现中,我们使用了一个结构体Stack来存储栈,其中top表示当前栈顶的位置。当我们要压入一个元素时,我们先判断栈是否已满,如果未满,我们将top向上移动一个位置,并将元素压入该位置。当我们要弹出一个元素时,我们先判断栈是否为空,如果不为空,我们将top向下移动一个位置,并返回该位置的元素值。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)