两栈共享空间C语言实现

 一次性定义两个栈

第一个栈的栈顶 top1 从-1开始递增

第二个栈的栈顶 top2 从maxlen开始递减

共享的意思是可以共享存储空间,即top1可以到maxlen-1,top2可以到0

栈满的标志是:top1+1 = top2

#include "stdio.h"    
#include "stdlib.h"   

#include "math.h"  
#include "time.h"

#define maxlen 20 /* 存储空间初始分配量 */



/* 两栈共享空间结构 */
typedef struct
{
    int data[maxlen];
    int top1;	/* 栈1栈顶指针 */
    int top2;	/* 栈2栈顶指针 */
}doubleStack;

int push(doubleStack* L, int value, int choose_stack)
{
    if (L->top1 + 1 == L->top2)
    {
        printf("栈满\n");
        return 0;
    }
    if (choose_stack == 1)
    {
        L->top1++;
        L->data[L->top1] = value;
    }
    else if(choose_stack == 2)
    {
        L->top2--;
        L->data[L->top2] = value;
    }
    else
    {
        printf("输入错误\n");
        return 0;
    }
    return 1;

}

int pop(doubleStack* L, int *value,int choose_stack)
{
    if (choose_stack == 1)
    {
        if (L->top1 == -1)
        {
            printf("栈1已满\n");
            return 0;
        } 
        *value = L->data[L->top1];
        L->top1--;
    }
    else if (choose_stack == 2)
    {
        if (L->top2 == maxlen)
        {
            printf("栈2已满\n");
            return 0;
        }
        *value = L->data[L->top2];
        L->top2++;
    }
    return 1;
}

int seelist(doubleStack L)
{
    printf("\n栈1:");
    for (int i = 0; i <= L.top1; i++)
    {
        printf("%d ", L.data[i]);
    }
    printf("\n栈2:");
    for (int j = maxlen-1;j>= L.top2; j--)
    {
        printf("%d ", L.data[j]);
    }
    return 1;
}

int initlist(doubleStack* L)
{
    L->top1 = -1;
    L->top2 = maxlen;
    return 1;
}

int main()
{
    int value, i, j;
    doubleStack L;
    initlist(&L);
    for (i = 0; i < 7; i++)
    {
        push(&L, i, 1);
    }
    for (i = 0; i < 4; i++)
    {
        push(&L, i, 2);
    }
    seelist(L);

    pop(&L, &value, 1);
    pop(&L, &value, 1);
    pop(&L, &value, 2);
    seelist(L);
    printf("\n%d", value);

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值