72
5.c
Normal file
72
5.c
Normal file
@@ -0,0 +1,72 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct Stacks stacks;
|
||||
struct Stacks {
|
||||
int *stack;
|
||||
uint s1, s2;
|
||||
uint l1, l2;
|
||||
};
|
||||
|
||||
stacks *init(uint s1, uint s2) {
|
||||
stacks *s = malloc(sizeof(stacks));
|
||||
s->stack = malloc(sizeof(int) * (s1 + s2));
|
||||
s->s1 = s1, s->s2 = s2;
|
||||
s->l1 = s->l2 = 0;
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
void push(uint stack, stacks *s, int elem) {
|
||||
if (stack != 1 && stack != 2)
|
||||
fprintf(stderr, "Invalid stack number\n");
|
||||
|
||||
if (stack == 1) {
|
||||
if (s->l1 == s->s1) {
|
||||
fprintf(stderr, "Stack 1 Overflow");
|
||||
return;
|
||||
}
|
||||
s->stack[s->l1++] = elem;
|
||||
return;
|
||||
}
|
||||
|
||||
if (s->l2 == s->s2) {
|
||||
fprintf(stderr, "Stack 2 Overflow");
|
||||
return;
|
||||
}
|
||||
s->stack[s->s1 + s->l2++] = elem;
|
||||
}
|
||||
|
||||
int pop(uint stack, stacks *s) {
|
||||
if (stack != 1 && stack != 2)
|
||||
fprintf(stderr, "Invalid stack number\n");
|
||||
|
||||
if (stack == 1) {
|
||||
if (!s->l1) {
|
||||
fprintf(stderr, "Stack 1 Underflow");
|
||||
exit(1);
|
||||
}
|
||||
return s->stack[--s->l1];
|
||||
}
|
||||
|
||||
if (!s->l2) {
|
||||
fprintf(stderr, "Stack 2 Underflow");
|
||||
exit(1);
|
||||
}
|
||||
return s->stack[s->s1 + --s->l2];
|
||||
}
|
||||
|
||||
int main() {
|
||||
int s1 = 8, s2 = 4; // sizes
|
||||
stacks *s = init(s1, s2);
|
||||
push(1, s, 3);
|
||||
push(1, s, 99);
|
||||
push(2, s, 6);
|
||||
push(1, s, 4);
|
||||
|
||||
printf("%d ", pop(1, s));
|
||||
printf("%d", pop(2, s));
|
||||
|
||||
free(s->stack);
|
||||
free(s);
|
||||
}
|
Reference in New Issue
Block a user