考研 408 × 求职面试
知识点 · 数据结构 · 基础
每日一题 · 数据结构
解析
面试小贴士 · 数据结构
代码实现 · C
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
typedef struct {
Node *top;
} Stack;
void init(Stack *s) { s->top = NULL; }
int empty(Stack *s) { return s->top == NULL; }
void push(Stack *s, int x) {
Node *p = (Node*)malloc(sizeof(Node));
p->val = x;
p->next = s->top;
s->top = p;
}
int pop(Stack *s, int *x) {
if (empty(s)) return 0;
Node *p = s->top;
*x = p->val;
s->top = p->next;
free(p);
return 1;
}
int main(void) {
Stack s; init(&s);
push(&s, 1); push(&s, 2);
int x;
while (pop(&s, &x)) printf("%d ", x); // 输出 2 1
return 0;
}