一个数组实现两个堆栈
2017-11-20 14:50
841 查看
堆栈的定义
#define MAXSIZE 100 typedef struct SNode *Stack; typedef struct SNode{ ElementType Data[MAXSIZE]; int Top; };
入栈操作
void Push(Stack PtrS,ElementType item){ if(PtrS->Top==MAXSIZE-1){ printf("stack is full."); return; }else{ PtrS->Data[++PtrS->Top]=item; return; } }
出栈操作
ElementType Pop(Stack PtrS){ if(PtrS->Top==-1){ printf("stack is empty."); return ERROR; }else{ return PtrS->Data[(PtrS->Top)--]; } }
[例]请用一个数组实现两个堆栈,要求最大地利用数组空间,使得数组只要有空间入栈操作就可以成功
/*分析*/ /*一种比较聪明的方法是使得这两个栈分别从数组两头开始向中间生长,当两个栈的栈顶指针相遇时,表示两个栈都满了 */ #include <stdio.h> #include <stdlib.h> #define MaxSize 10 #define ElementType int typedef struct DStack *Stack; struct DStack{ ElementType Data[MaxSize]; int Top1; int Top2; }; void Push(Stack PtrS,ElementType item,int Tag){ if(PtrS->Top2-PtrS->Top1== 1){ //堆栈已满 printf("stack is full."); return; } if(Tag == 1){ //对第一个堆栈操作 PtrS->Data[(++PtrS->Top1)] = item; }else{ //对第二个堆栈操作 PtrS->Data[(--PtrS->Top2)] = item; } } ElementType Pop(Stack PtrS,int Tag){ if(Tag==1){ if(PtrS->Top1==-1){ printf("stack1 is empty."); return NULL; }else return PtrS->Data[(PtrS->Top1)--]; } else{ if(PtrS->Top2 == MaxSize){ printf("stack2 is empty."); return NULL; }else return PtrS->Data[(PtrS->Top2++)]; } } void PrintStack( Stack PtrS, int Tag ){ if(Tag==1){ printf("Pop from Stack %d: ",Tag); while((PtrS->Top1)!=-1){ printf("%d ",PtrS->Data[(PtrS->Top1)--]); } putchar('\n'); }else{ printf("Pop from Stack %d: ",Tag); while((PtrS->Top2)!=MaxSize){ printf("%d ",PtrS->Data[(PtrS->Top2)++]); } putchar('\n'); } } int main(){ int N, Tag, X; Stack S; S->Top1=-1; S->Top2=MaxSize; scanf("%d %d", &Tag, &X); Push(S, X, Tag); scanf("%d", &Tag); X = Pop(S, Tag); PrintStack(S, 1); PrintStack(S, 2); return 0; }
相关文章推荐
- 在一个数组中实现两个堆栈
- 一个数组实现两个堆栈的c++实现与测试
- 在一个数组中实现两个堆栈
- 数据结构与算法——在一个数组中实现两个堆栈(C语言)
- PTA数据结构与算法题目集(中文)4-7 在一个数组中实现两个堆栈 (20分)
- 4-7 在一个数组中实现两个堆栈 (20分) PTA
- 4-7 在一个数组中实现两个堆栈 (20分)
- 6-3 在一个数组中实现两个堆栈(20 分)-pta_same_无聊的水体
- 4-7 在一个数组中实现两个堆栈
- 数据结构:请用一个数组实现两个堆栈,要求最大地利用数组空间,使 数组只要有空间入栈操作就可以成功
- 用一个数组实现两个堆栈,最大地使用数组的空间,只要有空间就能入栈成功
- 4-7 在一个数组中实现两个堆栈
- 4-7 在一个数组中实现两个堆栈 (20分)
- 4-7 在一个数组中实现两个堆栈 (20分)
- 4-7 在一个数组中实现两个堆栈 (20分)
- Java实现把两个数组合并为一个的方法总结
- 面试题之两个栈实现一个队列,乘机数组问题
- 一个数组实现两个栈(共享栈)
- 【数据结构】栈面试题--一个数组实现两个栈
- 有两个升序排列的数组A1和A2,给A1开辟的剩余内存有足够空间容纳A1,请实现一个函数,把A2中所有数字插入到A1中,并且是按照升序排列的