您的位置:首页 > 其它

一个数组实现两个堆栈

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: