共享栈

作者: 又是一只小白鼠 | 来源:发表于2020-04-08 22:04 被阅读0次

    利用栈底为止相对不变的特性,可让两个顺序栈共享一个一维数组空间,将两个栈的栈底分别设置在共享空间的两端,两个栈顶向共享空间的中间延伸。

    stack.png
    //
    //  sharestack.c
    //  Ccode
    //
    //  Created by XX on 2020/4/8.
    //  Copyright © 2020 XX. All rights reserved.
    //
    
    #include "sharestack.h"
    #include <stdlib.h>
    #define MAX 
    
    #define MaxSize 5//定义栈中元素的最大个数
    typedef int ElemType;
    typedef struct shareStack {
        ElemType data[MaxSize];
        int top0;
        int top1;
    }shareStack, *pshare;
    
    
    pshare CreateShare() {
        pshare p = (shareStack *)malloc(sizeof(shareStack));
        p->top0 = -1;
        p->top1 = MaxSize;
        return p;
    }
    
    //判空
    int EmptyShare(pshare p) {
        if (p->top0 == -1 && p->top1 == MaxSize) {
            return 0;
        }
        return -1;
    }
    
    //入栈
    int PushShare(pshare p, ElemType data, int stackNum) {
        if (p == NULL) {
            exit(-1);
        }
        if (p->top0 + 1 == p->top1) {
            printf("栈满...\n");
            return 0;
        }
        switch (stackNum) {
            case 0:
                p->top0 ++;
                p->data[p->top0] = data;
                return 0;
            case 1:
                p->top1 --;
                p->data[p->top1] = data;
                return 0;
                
            default:
                return -1;
        }
    }
    
    //出栈
    int PopShare(pshare p, int stackNum) {
        int data;
        if (p == NULL) {
            exit(-1);
        }
        if (p->top0 == -1 && p->top1 == MaxSize) {
            return -1;
        }
        switch (stackNum) {
            case 0:
                data = p->data[p->top0];
                p->top0 --;
                return data;
            case 1:
                data = p->data[p->top1];
                p->top1 ++;
                return data;
            default:
                return -1;
        }
    }
    
    
    void testshare() {
        int data;
        shareStack s;
        pshare top = &s;
        top = CreateShare();
        PushShare(top, 23, 0);
        PushShare(top, 23, 0);
        PushShare(top, 78, 0);
        PushShare(top, 23, 1);
        PushShare(top, 45, 1);
        PushShare(top, 34, 0);
        data = PopShare(top, 0);
        printf("%d\n", data);
    }
    

    相关文章

      网友评论

          本文标题:共享栈

          本文链接:https://www.haomeiwen.com/subject/eyzxmhtx.html