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

#define MAX_SIZE 4

typedef struct { char data[MAX_SIZE]; int top; } stack;

void push(stack *s, char c) { if (s->top == MAX_SIZE - 1) { printf("Stack is full\n"); exit(1); } s->data[++s->top] = c; }

char pop(stack *s) { if (s->top == -1) { printf("Stack is empty\n"); exit(1); } return s->data[s->top--]; }

int main() { stack s; s.top = -1;

// push 'A', 'B', 'C', 'D' into stack
push(&s, 'A');
push(&s, 'B');
push(&s, 'C');
push(&s, 'D');

// all impossible pop sequences
if (pop(&s) != 'D') {
    printf("Impossible\n");
}
if (pop(&s) != 'C' || pop(&s) != 'D') {
    printf("Impossible\n");
}
if (pop(&s) != 'B' || pop(&s) != 'C' || pop(&s) != 'D') {
    printf("Impossible\n");
}
if (pop(&s) != 'A' || pop(&s) != 'B' || pop(&s) != 'C' || pop(&s) != 'D') {
    printf("Impossible\n");
}

return 0;

}

C语言实现栈的出栈序列不可能情况

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

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