写一算法将一顺序栈中的元素依次取出,并打印元素值
时间: 2023-04-27 19:05:49 浏览: 493
1. 定义一个顺序栈,将元素依次入栈。
2. 循环遍历栈中的元素,每次取出栈顶元素并打印。
3. 直到栈为空,算法结束。
具体实现如下:
```
// 定义一个顺序栈
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;
}
// 入栈操作
void Push(SeqStack *s, int x) {
if (IsFull(s)) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = x;
}
// 出栈操作
int Pop(SeqStack *s) {
if (IsEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
// 遍历栈中的元素并打印
void PrintStack(SeqStack *s) {
while (!IsEmpty(s)) {
int x = Pop(s);
printf("%d ", x);
}
printf("\n");
}
// 测试代码
int main() {
SeqStack s;
InitStack(&s);
Push(&s, 1);
Push(&s, 2);
Push(&s, 3);
Push(&s, 4);
Push(&s, 5);
PrintStack(&s);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)