设计一种数据结构,满足栈的“后进先出”性质,实
现以下3种操作:
1)Push(v,S):将v压入到栈S;
2)Pop(S):弹出栈顶元素;
3)Maxelement(S):返回栈S中最大元素;
并且使每种操作的时间复杂度尽可能的低。
#pragma warning(disable :4996)
#include <stdio.h>
#define maxlength 1000
typedef int Element;//定义基础类型
typedef struct STACK {
int top;
Element ele[maxlength];
}STA;
bool empty(STA s) {//判断非空与否
return s.top == -1;
}
void makenull(STA *s) {//置栈为空
s->top = -1;
}
Element top(STA s) {//返回栈顶元素
if (empty(s)) {
return NULL;//栈为空返回为空
}
return s.ele[s.top];
}
Element pop(STA *s1, STA *s2) {//弹出栈顶元素并且返回栈顶元素
Element ch = s1->ele[s1->top];
if (s1->top < 0) {
makenull(s1);//栈为空则置空并返回空
return NULL;
}
else {
s1->top--;//出栈,返回原来栈顶元素
if (s2->ele[s2->top] == ch) {
s2->top--;
}
return ch;
}
}
void push(STA *s1, STA *s2, Element x) {//压栈
s1->ele[++s1->top] = x;
if (x > s2->ele[s2->top])
s2->ele[++s2->top] = x;
}
Element maxele(STA s) {
return s.ele[s.top];
}
int main() {
STA s1, s2;
makenull(&s1);
makenull(&s2);
int a;//1判断是否为空,2进栈,3出栈,4求最值
while (scanf("%d", &a) != EOF) {
switch (a) {
case 1:
printf("%d\t", empty(s1));
printf("%d\n", empty(s2));
break;
case 2:
Element x;
scanf("%d", &x);
push(&s1, &s2, x);
break;
case 3:
printf("%d\n", pop(&s1, &s2));
break;
case 4:
printf("%d\n", maxele(s2));
break;
}
}
return 0;
}