自定义栈实现:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
int val;
struct stack* top;
} stack;
stack* top = NULL;
int capacity = 0;
void push(int x) {
stack* newNode = malloc(sizeof(stack));
newNode->val = x;
newNode->top = top;
top = newNode;
++capacity;
}
void pop() {
if (capacity) {
stack* curTop = top;
top = curTop->top;
free(curTop);
--capacity;
} else {
puts("Empty");
}
}
void query() {
if (capacity) {
printf("%d\n", top->val);
} else {
puts("Empty");
}
}
void size() {
printf("%d\n", capacity);
}
int main() {
int n;
scanf("%d", &n);
while (n--) {
char szCmd[6];
int value;
scanf("%s", szCmd);
if (szCmd[0] == 'p') {
if (szCmd[1] == 'u') {
scanf("%d", &value);
push(value);
} else if (szCmd[1] == 'o') {
pop();
}
} else if (szCmd[0] == 'q') {
query();
} else if (szCmd[0] == 's') {
size();
}
}
return 0;
}

京公网安备 11010502036488号