参考书:数据结构教程 第5版 李葆春 P83
#include <stdio.h>
#include <string.h>
#include <stdlib.h>#define MaxSize 10/*共享栈*/
typedef struct
{char data[MaxSize];int top1,top2,len;
}DStack;/*初始化*/
void InitStack(DStack *s){s->top1=-1,s->top2=MaxSize,s->len=MaxSize;s=(DStack *)malloc(sizeof(DStack));printf("%s\n",s->data);
}/*销栈*/
void DestroyStack(DStack *s){free(s);
}/*判断栈是否为空*/
int StackEmpty(DStack *s, int i){/*对栈1操作*/if (i==1){return (s->top1==-1);}if (i==2){return (s->top2==MaxSize);}}/*进栈*/
void Push(DStack *s, int e, int i){if (i==1&&s->len>0){s->top1++;s->data[s->top1]=e;s->len--;}if (i==2&&s->len>0){s->top2--;s->data[s->top2]=e;s->len--;}
}/*出栈*/
void Pop(DStack *s, int *e, int i){if (i==1){*e=s->data[s->top1];s->top1--;}if (i==2){*e=s->data[s->top2];s->top2++;}
}/*取栈顶元素*/
void GetTop(DStack *s,int *e, int i){if (i==1){*e=s->data[s->top1];}if (i==2){*e=s->data[s->top2];}
}/*实例:输入两个字符串*/
void Input(char str1[], char str2[]){char e;DStack st;InitStack(&st);/*进栈*/for (int j = 0; str1[j]!='\0'; j++){Push(&st, str1[j], 1);}for (int k = 0; str2[k]!='\0'; k++){Push(&st, str2[k], 2);}/*判断栈空*/if(StackEmpty(&st,1)){printf("栈1空\n");}if (StackEmpty(&st,2)){printf("栈2空\n");}/*取栈顶*/GetTop(&st,&e,1);printf("栈1顶:%c\n",e);GetTop(&st,&e,2);printf("栈2顶:%c\n",e);/*出栈*/while (st.top1){Pop(&st,&e,1);printf("%c",e);}printf("\n");while (st.top2<MaxSize){Pop(&st,&e,2);printf("%c",e);}printf("\n");/*销栈*/DestroyStack(&st);// printf("%d\n",st.top1);// printf("%d\n",st.top2);// printf("%s",st.data);
}int main(){char str1[10]={"qwertyu"};char str2[10]={"zxcvb"};Input(str1, str2);
}