用c语言编写建立顺序栈,并在顺序栈上实现入栈和出栈操作,编程实现如下功能: 1.根据输入的栈中元素个数n和各元素值建立一个顺序栈,并输出栈中各元素值。 2.将数据元素e入栈,并输出入栈后的顺序栈中各元素值。 3.将顺序栈中的栈顶元素出栈,并输出出栈元素的值和出栈后顺序栈中各元素值。
时间: 2024-02-03 10:12:57 浏览: 88
下面是使用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;
}
// 入栈操作
void push(SeqStack *s, int e) {
if (isFull(s)) {
printf("Stack is full, push failed.\n");
return;
}
s->data[++s->top] = e;
}
// 出栈操作
int pop(SeqStack *s) {
if (isEmpty(s)) {
printf("Stack is empty, pop failed.\n");
return -1;
}
return s->data[s->top--];
}
// 输出栈中元素
void printStack(SeqStack *s) {
printf("Stack: ");
for (int i = 0; i <= s->top; i++) {
printf("%d ", s->data[i]);
}
printf("\n");
}
int main() {
SeqStack s;
int n, e;
// 1.根据输入的栈中元素个数n和各元素值建立一个顺序栈,并输出栈中各元素值。
printf("Please input the number of elements: ");
scanf("%d", &n);
printf("Please input %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &e);
push(&s, e);
}
printStack(&s);
// 2.将数据元素e入栈,并输出入栈后的顺序栈中各元素值。
printf("Please input the element to be pushed: ");
scanf("%d", &e);
push(&s, e);
printStack(&s);
// 3.将顺序栈中的栈顶元素出栈,并输出出栈元素的值和出栈后顺序栈中各元素值。
int popResult = pop(&s);
printf("Pop element: %d\n", popResult);
printStack(&s);
return 0;
}
```
运行结果如下:
```
Please input the number of elements: 4
Please input 4 elements: 1 2 3 4
Stack: 1 2 3 4
Please input the element to be pushed: 5
Stack: 1 2 3 4 5
Pop element: 5
Stack: 1 2 3 4
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)