106 lines
2 KiB
C
106 lines
2 KiB
C
|
#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;
|
||
|
}
|