#include <stdio.h> #include <stdlib.h>

#define MAX_SIZE 100

typedef struct { int data[MAX_SIZE]; int top; } Stack;

void init(Stack *s) { s->top = -1; }

int is_empty(Stack *s) { return s->top == -1; }

int is_full(Stack *s) { return s->top == MAX_SIZE - 1; }

void push(Stack *s, int x) { if (is_full(s)) { printf("Stack Overflow\n"); exit(1); } s->data[++s->top] = x; }

int pop(Stack *s) { if (is_empty(s)) { printf("Stack Underflow\n"); exit(1); } return s->data[s->top--]; }

int top(Stack *s) { if (is_empty(s)) { printf("Stack Underflow\n"); exit(1); } return s->data[s->top]; }

void reverse(Stack *s) { if (!is_empty(s)) { int x = pop(s); reverse(s); push(s, x); } }

int main() { Stack s; init(&s);

push(&s, 1);
push(&s, 2);
push(&s, 3);

printf("Original Stack:\n");
while (!is_empty(&s)) {
    printf("%d ", pop(&s));
}
printf("\n");

push(&s, 1);
push(&s, 2);
push(&s, 3);

reverse(&s);

printf("Reversed Stack:\n");
while (!is_empty(&s)) {
    printf("%d ", pop(&s));
}
printf("\n");

return 0;

}

题目:用递归颠倒一个栈。C语言实现。

原文地址: https://www.cveoy.top/t/topic/b4GV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录