练习 #4
Coddy 栈:数据结构系列 #1 课程的第 12 课,共 13 课。
让我们创建一个最小值/最大值栈!
挑战
简单在之前的 Stack 类中添加两个函数:
min:返回当前栈中的最小值。max:返回当前栈中的最大值。
加分项:尽量不要在每次 push 或 pop 时遍历栈中的所有元素。
亲手试试
#include <stdio.h>
#include <string.h>
#include "stack.h"
int main() {
Stack stack;
Stack_init(&stack);
char cmd[16];
while (scanf("%15s", cmd) == 1) {
if (strcmp(cmd, "push") == 0) {
int x;
scanf("%d", &x);
Stack_push(&stack, x);
}
else if (strcmp(cmd, "pop") == 0) {
printf("%d\n", Stack_pop(&stack));
}
else if (strcmp(cmd, "top") == 0) {
printf("%d\n", Stack_top(&stack));
}
else if (strcmp(cmd, "size") == 0) {
printf("%d\n", Stack_size(&stack));
}
else if (strcmp(cmd, "min") == 0) {
printf("%d\n", Stack_min(&stack));
}
else if (strcmp(cmd, "max") == 0) {
printf("%d\n", Stack_max(&stack));
}
}
return 0;
}
栈:数据结构系列 #1中的所有课
自己练习: C 在线编译器