题目: 请用一个数组实现两个堆栈,要求最大的利用数组空间,使数组只要有空间入栈操作就可以成功。
思路:
-
中间为栈底,两头为栈顶
-
两头为栈底,栈顶向内扩张
很明显,思路2符合要求。 思路1 虽然实现了用一个数组实现两个堆栈,但是当stack1满,而stack2未满时,再无法向stack1插入元素,同时因stack2的剩余空间无法得到使用而造成了空间浪费。思路2不存在stack1或者stack2满的限制,直到两个堆栈占满整个数组空间才无法继续压入元素。因此,思路2 不仅实现了用一个数组实现两个堆栈,而且实现了只要有空间入栈操作就可以成功,最大地利用了数组空间。
代码实现:
#include "stdio.h"
#include "stdlib.h"
#define MaxSize 10
struct DStack{
int Data[MaxSize];
int top1;
int top2;
};
int Push(struct DStack *PtrD,int X,int Tag){
if(PtrD->top2-PtrD->top1==1){
printf("堆栈满!\n");
return false;
}else{
if(Tag==1){
PtrD->Data[++(PtrD->top1)]=X;
}else{
PtrD->Data[--(PtrD->top2)]=X;
}
return true;
}
}
int Pop(struct DStack *PtrD,int Tag){
if(Tag==1){
if(PtrD->top1==-1){
printf("堆栈1空!\n");
return NULL;
}else{
return (PtrD->Data[(PtrD->top1)--]);
}
}else{
if(PtrD->top2==MaxSize){
printf("堆栈2空!\n");
return NULL;
}else{
return (PtrD->Data[(PtrD->top2)++]);
}
}
}
int main(){
struct DStack S;
S.top1=-1;
S.top2=MaxSize;
Pop(&S,1);
Pop(&S,2);
printf("%d\n",Push(&S,1,1));
printf("%d\n",Push(&S,2,1));
printf("%d\n",Push(&S,1,2));
printf("%d\n",Push(&S,2,2));
printf("%d\n",Pop(&S,1));
printf("%d\n",Pop(&S,1));
printf("%d\n",Pop(&S,2));
printf("%d\n",Pop(&S,2));
return 0;
}
运行结果:
**