栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言数据结构——在一个数组中实现两个堆栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言数据结构——在一个数组中实现两个堆栈

直接上代码:

#include 
#include 

#define ERROR 1e8
typedef int ElementType;
typedef enum { push, pop, end } Operation;
typedef enum { false, true } bool;
typedef int Position;
struct SNode {
    ElementType *Data;    //虽然是指针类型可以当作数组用
    Position Top1, Top2;  //实现动态定义数组大小
    int MaxSize;
};
typedef struct SNode *Stack;

Stack CreateStack( int MaxSize );
bool Push( Stack S, ElementType X, int Tag );
ElementType Pop( Stack S, int Tag );

Operation GetOp(); 
void PrintStack( Stack S, int Tag ); 

int main()
{
    int N, Tag, X;
    Stack S;
    int done = 0;

    scanf("%d", &N);
    S = CreateStack(N);
    while ( !done ) {
        switch( GetOp() ) {
        case push: 
            scanf("%d %d", &Tag, &X);
            if (!Push(S, X, Tag)) printf("Stack %d is Full!n", Tag);
            break;
        case pop:
            scanf("%d", &Tag);
            X = Pop(S, Tag);
            if ( X==ERROR ) printf("Stack %d is Empty!n", Tag);
            break;
        case end:
            PrintStack(S, 1);
            PrintStack(S, 2);
            done = 1;
            break;
        }
    }
    return 0;
}


Operation GetOp()   //操作方式
{
    char ch[10];
    scanf("%s",ch);
    switch (ch[1])
    {
    case('u'):return push;
    case('o'):return pop;
    case('n'):return end;
    }
}
void PrintStack( Stack S, int Tag )  //输出栈
{
    
    if(Tag==1)
    {
        printf("Pop from Stack 1:");
        while(S->Top1!=-1)
            {printf("%d ",S->Data[(S->Top1)--]);}
        printf("n");
    }
    else
    {
        printf("Pop from Stack 2:");
        while(S->Top2!=S->MaxSize)
            {printf("%d ",S->Data[(S->Top2)++]);}
    }
}

Stack CreateStack( int MaxSize )    //创建栈
{
    Stack S;
    S=(Stack)malloc(sizeof(struct SNode));  //S为指针类型,若没有为其分配空间则无法进行下面的分配空间和赋值操作
    S->Data=(int*)malloc(4*MaxSize);
    S->MaxSize=MaxSize;
    S->Top1=-1;
    S->Top2=MaxSize;
    return S;
}
bool Push( Stack S, ElementType X, int Tag )  //入栈
{
    if(S->Top2-S->Top1==1)
    {printf("Stack Fulln");    return false;}
    if(Tag==1)
        S->Data[++(S->Top1)]=X;
    else
        S->Data[--(S->Top2)]=X;
    return true;
}
ElementType Pop( Stack S, int Tag )   //出栈
{
    if(Tag==1)
    {
        if(S->Top1==-1)
        {printf("Stack 1 Emptyn");    return ERROR;}
        else
            return S->Data[(S->Top1)--];
    }
    else
    {
        if(S->Top2==S->MaxSize)
        {printf("Stack 2 Emptyn");    return ERROR;}
        else
            return S->Data[(S->Top2)++];
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/330085.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号