双栈共享
雙棧共享之數組實現
雙棧的結構體構建
初始化創建
Stack CreateStack( int MaxSize ){Stack S=(Stack)malloc(sizeof(struct SNode));S->Data=(int *)malloc(MaxSize*sizeof(int));//為動態數組分配空間S->MaxSize=MaxSize;S->Top1=-1;//第一個棧的棧頂指向頭S->Top2=MaxSize;//第二個棧的棧頂指向尾return S;}雙棧判空
int IsEmpty(Stack S,int Tag) {//分別判斷兩個棧的空的條件if(Tag==1&&S->Top1==-1)return 1;else if(Tag==2&&S->Top2==S->MaxSize)return 1;return 0; }雙棧判滿
int IsFull(Stack S) {if(S->Top2-S->Top1==1&&(S->Top1!=-1||S->Top2!=S->MaxSize))//兩個棧不空且位置之差為1return 1;return 0; }入棧
bool Push( Stack S, int X, int Tag ) {if(S->Top2-S->Top1==1)//if(S->top==S->MaxSize){//先判滿printf("Stack Full\n");return false;}switch(Tag){//分情況入棧case 1:{S->Data[++(S->Top1)]=X;return true;break;}case 2:{S->Data[--(S->Top2)]=X;return true;break;}default:break;} } int Pop( Stack S, int Tag ) {if(Tag==1){if(S->Top1==-1){printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top1)--];}else{if(S->Top2==S->MaxSize){printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top2)++];}}出棧
int Pop( Stack S, int Tag ) {if(Tag==1){if(S->Top1==-1)//空{printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top1)--];}else{if(S->Top2==S->MaxSize)//空{printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top2)++];}} #include<stdio.h> #include<stdlib.h> #define ERROR 1e8 typedef struct SNode{int *Data;int MaxSize;int Top1,Top2; }SNode,*Stack;Stack CreateStack( int MaxSize ){Stack S=(Stack)malloc(sizeof(struct SNode));S->Data=(int *)malloc(MaxSize*sizeof(int));S->MaxSize=MaxSize;S->Top1=-1;S->Top2=MaxSize;return S;} bool Push( Stack S, int X, int Tag ) {if(S->Top2-S->Top1==1)//if(S->top==S->MaxSize){printf("Stack Full\n");return false;}switch(Tag){case 1:{S->Data[++(S->Top1)]=X;return true;break;}case 2:{S->Data[--(S->Top2)]=X;return true;break;}default:break;} } int Pop( Stack S, int Tag ) {if(Tag==1){if(S->Top1==-1){printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top1)--];}else{if(S->Top2==S->MaxSize){printf("Stack %d Empty\n",Tag);return ERROR;}return S->Data[(S->Top2)++];}} int IsEmpty(Stack S,int Tag) {if(Tag==1&&S->Top1==-1)return 1;else if(Tag==2&&S->Top2==S->MaxSize)return 1;return 0; } int IsFull(Stack S) {if(S->Top2-S->Top1==1&&(S->Top1!=-1||S->Top2!=S->MaxSize))return 1;return 0; } int main() {int n,Tag,X;scanf("%d",&n);struct SNode *S;S=CreateStack(n);for(int i=0;i<n;i++){ scanf("%d%d",&X,&Tag);Push(S,X,Tag);}scanf("%d",&Tag);int y;while(!IsEmpty(S,Tag)){y=Pop(S,Tag);printf("%d\n",y);}return 0; }總結
- 上一篇: Visual Studio2012 编译
- 下一篇: java 水晶报表教程_水晶报表 (Cr