This commit is contained in:
juan 2022-09-24 13:53:33 +08:00
parent 4e0691c286
commit 94d71d98d9
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7

View file

@ -0,0 +1,105 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct doubleStack {
int capacity;
int top1;
int top2;
int *arr;
} doubleStack;
doubleStack *createStack(int capacity) {
doubleStack *new = malloc(sizeof(doubleStack));
new->capacity = capacity;
new->top1 = -1;
new->top2 = capacity;
if (capacity <= 0) {
return NULL;
}
new->arr = malloc(sizeof(int) * capacity);
return new;
}
void removeStack(doubleStack *st) {
free(st->arr);
free(st);
}
void push(doubleStack *st, int in, int side) {
// side == 0: top1
// side == 1: top2
if (st->top1 == st->top2 - 1) {
printf("ERR: array is full\n");
return;
}
if (side == 0) {
st->top1++;
st->arr[st->top1] = in;
} else {
st->top2--;
st->arr[st->top2] = in;
}
}
int top(doubleStack *st, int side) {
if (side == 0) {
return st->arr[st->top1];
} else {
return st->arr[st->top2];
}
}
int isEmpty(doubleStack *st, int side) {
if (side == 0) {
return (st->top1 == -1);
} else {
return (st->top2 == st->capacity);
}
}
void pop(doubleStack *st, int side) {
if (!isEmpty(st, side)) {
if (side == 0) {
st->top1--;
} else {
st->top2--;
}
} else {
printf("ERR: array is empty\n");
}
}
int main(void) {
doubleStack* test = createStack(5);
push(test, 1, 0);
printf("Top of left stack is %d\n", top(test, 0));
push(test, 2, 0);
printf("Top of left stack is %d\n", top(test, 0));
push(test, 3, 0);
printf("Top of left stack is %d\n", top(test, 0));
push(test, 4, 0);
printf("Top of left stack is %d\n", top(test, 0));
push(test, 5, 0);
printf("Top of left stack is %d\n", top(test, 0));
push(test, 6, 0);
printf("Top of left stack is %d\n", top(test, 0));
pop(test, 0);
push(test, 6, 0);
printf("Top of left stack is %d\n", top(test, 0));
pop(test, 0);
pop(test, 0);
push(test, 9, 1);
printf("Top of right stack is %d\n", top(test, 1));
push(test, 8, 1);
printf("Top of right stack is %d\n", top(test, 1));
removeStack(test);
return 0;
}