顺序栈之共享栈实现——C语言

参考书:数据结构教程 第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);
}

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值