包含二维数组的栈C语言
时间: 2023-05-18 08:03:04 浏览: 78
实现二维数组的栈可以使用一个一维数组来存储数据,然后使用指针来模拟二维数组的访问。具体实现可以参考以下代码:
#define ROWS 10
#define COLS 10
typedef struct {
int data[ROWS * COLS];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int push(Stack *s, int x, int y, int value) {
if (s->top >= ROWS * COLS - 1) {
return 0;
}
int index = x * COLS + y;
s->data[index] = value;
s->top++;
return 1;
}
int pop(Stack *s, int x, int y) {
if (s->top < 0) {
return 0;
}
int index = x * COLS + y;
int value = s->data[index];
s->top--;
return value;
}
int main() {
Stack s;
init(&s);
push(&s, 0, 0, 1);
push(&s, 0, 1, 2);
push(&s, 1, 0, 3);
push(&s, 1, 1, 4);
printf("%d\n", pop(&s, 1, 1)); // output: 4
printf("%d\n", pop(&s, 1, 0)); // output: 3
printf("%d\n", pop(&s, 0, 1)); // output: 2
printf("%d\n", pop(&s, 0, 0)); // output: 1
return 0;
}