用C语言实现:1.根据输入的栈中元素个数n和各元素值建立一个顺序栈,并输出栈中各元素值。 2.将数据元素e入栈,并输出入栈后的顺序栈中各元素值。 3.将顺序栈中的栈顶元素出栈,并输出出栈元素的值和出栈后顺序栈中各元素值。
时间: 2024-02-01 08:15:45 浏览: 24
实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 定义栈的最大长度
typedef struct {
int data[MAX_SIZE]; // 存储栈中元素的数组
int top; // 栈顶指针,初始值为-1
} SeqStack;
void init(SeqStack *s) {
s->top = -1; // 初始化栈顶指针
}
int is_empty(SeqStack *s) {
return s->top == -1; // 栈顶指针为-1表示栈为空
}
int is_full(SeqStack *s) {
return s->top == MAX_SIZE - 1; // 栈顶指针为MAX_SIZE-1表示栈满
}
void push(SeqStack *s, int e) {
if (is_full(s)) {
printf("Error: stack is full.\n");
return;
}
s->top++; // 栈顶指针加1
s->data[s->top] = e; // 将元素e压入栈顶
}
int pop(SeqStack *s) {
if (is_empty(s)) {
printf("Error: stack is empty.\n");
return -1;
}
int e = s->data[s->top]; // 取出栈顶元素
s->top--; // 栈顶指针减1
return e;
}
void print(SeqStack *s) {
if (is_empty(s)) {
printf("The stack is empty.\n");
return;
}
printf("The elements of the stack are: ");
for (int i = 0; i <= s->top; i++) {
printf("%d ", s->data[i]);
}
printf("\n");
}
int main() {
SeqStack s;
init(&s); // 初始化栈
int n, e;
printf("Input the number of elements in the stack: ");
scanf("%d", &n);
printf("Input the elements of the stack: ");
for (int i = 0; i < n; i++) {
scanf("%d", &e);
push(&s, e); // 入栈
}
print(&s); // 输出栈中元素
printf("Input the element to push into the stack: ");
scanf("%d", &e);
push(&s, e); // 入栈
print(&s); // 输出栈中元素
int top = pop(&s); // 出栈
printf("The popped element is: %d\n", top);
print(&s); // 输出栈中元素
return 0;
}
```
运行程序,输入如下:
```
Input the number of elements in the stack: 3
Input the elements of the stack: 1 2 3
Input the element to push into the stack: 4
```
输出如下:
```
The elements of the stack are: 1 2 3
The elements of the stack are: 1 2 3 4
The popped element is: 4
The elements of the stack are: 1 2 3
```