用C语言实现:1.根据输入的栈中元素个数n和各元素值建立一个顺序栈,并输出栈中各元素值。 2.将数据元素e入栈,并输出入栈后的顺序栈中各元素值。 将顺序栈中的栈顶元素出栈,并输出出栈元素的值和出栈后顺序栈中各元素值。
时间: 2024-02-01 18:13:11 浏览: 24
下面是用 C 语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 栈结构体定义
typedef struct {
int data[MAX_SIZE];
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 == MAX_SIZE - 1;
}
// 入栈
void Push(SeqStack *s, int e) {
if (IsFull(s)) {
printf("Stack overflow!\n");
exit(1);
} else {
s->data[++s->top] = e;
}
}
// 出栈
int Pop(SeqStack *s) {
if (IsEmpty(s)) {
printf("Stack underflow!\n");
exit(1);
} else {
return s->data[s->top--];
}
}
// 输出栈中元素
void PrintStack(SeqStack *s) {
int i;
for (i = 0; i <= s->top; i++) {
printf("%d ", s->data[i]);
}
printf("\n");
}
int main() {
SeqStack s;
int n, e, i;
// 输入栈中元素个数n
printf("Enter the number of elements in the stack: ");
scanf("%d", &n);
// 建立栈
printf("Enter the elements of the stack:\n");
for (i = 0; i < n; i++) {
scanf("%d", &e);
Push(&s, e);
}
// 输出栈中元素
printf("The stack elements are: ");
PrintStack(&s);
// 将数据元素e入栈,并输出入栈后的顺序栈中各元素值
printf("Enter an element to push into the stack: ");
scanf("%d", &e);
Push(&s, e);
printf("The stack elements after push are: ");
PrintStack(&s);
// 将顺序栈中的栈顶元素出栈,并输出出栈元素的值和出栈后顺序栈中各元素值
e = Pop(&s);
printf("The popped element is: %d\n", e);
printf("The stack elements after pop are: ");
PrintStack(&s);
return 0;
}
```
注意:此处的顺序栈采用的是数组实现,而不是链表实现,因此需要定义一个栈顶指针 top 来表示栈顶元素的位置。