- #include <stdio.h>
- #include <stdlib.h>
- #define MAXNUM 4
- #define OVERFLOW -1
- #define UNDERFLOW -2
- #define FLAGERROR -3
- typedef int elemtype;
- typedef struct stack
- {
- int top;
- int flag;
- }stack;
- typedef struct ShareArrStack
- {
- elemtype data[MAXNUM];
- stack stack1;
- stack stack2;
- }ShareArrStack;
- void InitStack(ShareArrStack *s)
- {
- (s->stack1).top = -1;
- (s->stack1).flag = 1;
- (s->stack2).top = MAXNUM;
- (s->stack2).flag = 2;
- }
- int IsFull(ShareArrStack *s)
- {
- return (s->stack1.top + 1 == s->stack2.top);
- }
- int IsEmpty(stack *sn)
- {
- return ((sn->top == -1)||(sn->top == MAXNUM));
- }
- void Push(ShareArrStack *s,stack sn,elemtype x)
- {
- if (IsFull(s))
- {
- printf("Stack overflow!");
- exit(OVERFLOW);
- }
- else
- {
- switch(sn.flag)
- {
- case 1:
- {
- s->stack1.top += 1;
- s->data[s->stack1.top] = x;
- break;
- }
- case 2:
- {
- s->stack2.top -= 1;
- s->data[s->stack2.top] = x;
- break;
- }
- default:
- {
- exit(FLAGERROR);
- }
- }
- }
- }
- elemtype Pop(ShareArrStack *s,stack sn)
- {
- if (IsEmpty(&sn))
- {
- printf("stack underflow!");
- exit(UNDERFLOW);
- }
- else
- {
- switch(sn.flag)
- {
- case 1:
- {
- return (s->data[s->stack1.top --]);
- break;
- }
- case 2:
- {
- return (s->data[s->stack2.top ++]);
- break;
- }
- default:
- {
- exit(FLAGERROR);
- }
- }
- }
- }
- int main()
- {
- ShareArrStack *s = NULL;
- s = (ShareArrStack *)malloc(sizeof(ShareArrStack));
- InitStack(s);
- Push(s,s->stack1,1);
- Push(s,s->stack2,9);
- Push(s,s->stack1,2);
- Push(s,s->stack2,8);
- printf("%d, ",Pop(s,s->stack2));
- printf("%d",Pop(s,s->stack1));
- return 0;
- }
[root@localhost C++]# ./Arr2Stack
8, 2[root@localhost C++]#
阅读(2757) | 评论(0) | 转发(1) |