Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct elem
- {
- int val;
- int max;
- };
- struct stack
- {
- struct elem *data;
- int cap;
- int top1;
- int top2;
- };
- void InitDoubleStack(struct stack *q, int n)
- {
- q->data = calloc(n, sizeof(struct elem));
- q->cap = n;
- q->top1 = 0;
- q->top2 = n - 1;
- }
- int StackEmpty1(struct stack *q)
- {
- return (q->top1 == 0) ? 1 : 0;
- }
- int StackEmpty2(struct stack *q)
- {
- return (q->top2 == q->cap - 1) ? 1 : 0;
- }
- void Push1(struct stack *q, int x)
- {
- q->data[q->top1].val = x;
- if (!StackEmpty1(q) && (q->data[q->top1 - 1].max > x))
- q->data[q->top1].max = q->data[q->top1 - 1].max;
- else
- q->data[q->top1].max = x;
- q->top1++;
- }
- void Push2(struct stack *q, int x)
- {
- q->data[q->top2].val = x;
- if (!StackEmpty2(q) && (q->data[q->top2 + 1].max > x))
- q->data[q->top2].max = q->data[q->top1 + 1].max;
- else
- q->data[q->top2].max = x;
- q->top2--;
- }
- struct elem Pop1(struct stack *q)
- {
- q->top1--;
- return q->data[q->top1];
- }
- struct elem Pop2(struct stack *q)
- {
- q->top2++;
- return q->data[q->top2];
- }
- void InitQueue(struct stack *q, int n)
- {
- InitDoubleStack(q, n);
- }
- int QueueEmpty(struct stack *q)
- {
- return (StackEmpty1(q) && StackEmpty2(q)) ? 1 : 0;
- }
- void Enqueue(struct stack *q, int x)
- {
- Push1(q, x);
- }
- int Dequeue(struct stack *q)
- {
- if (StackEmpty2(q))
- while ((StackEmpty1(q)) == 0)
- Push2(q, Pop1(q).val);
- return Pop2(q).val;
- }
- int Max(struct stack *q)
- {
- if (StackEmpty1(q))
- return q->data[q->top2 + 1].max;
- else if (StackEmpty2(q))
- return q->data[q->top1 - 1].max;
- else
- return (q->data[q->top2 + 1].max > q->data[q->top1 - 1].max) ?
- q->data[q->top2 + 1].max : q->data[q->top1 - 1].max;
- }
- int main()
- {
- int i, n, x;
- char s[6];
- scanf("%d", &n);
- struct stack abc;
- InitQueue(&abc, n);
- for (i = 0; i < n; i++)
- {
- scanf("%s", s);
- if (strcmp(s, "EMPTY") == 0)
- if (QueueEmpty(&abc))
- printf("true\n");
- else
- printf("false\n");
- else if (strcmp(s, "MAX") == 0)
- printf("%d\n", Max(&abc));
- else if (strcmp(s, "DEQ") == 0)
- printf("%d\n", Dequeue(&abc));
- else if (strcmp(s, "ENQ") == 0)
- {
- scanf("%d", &x);
- Enqueue(&abc, x);
- }
- }
- free(abc.data);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement