标题:刚敲了个栈的动态顺序存储的代码,跟大家交流交流,分享分享。
只看楼主
我爱敲代码
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:70
专家分:165
注 册:2013-4-23
结帖率:85.71%
 问题点数:0 回复次数:0 
刚敲了个栈的动态顺序存储的代码,跟大家交流交流,分享分享。
#define OK 1
#define ERROR -1
#define STACK_MAX_SIZE 100
#define increment 50
#include"stdio.h"
#include"stdlib.h"
typedef int  ElemType;
typedef int  status;
typedef struct Stack_node
{
  ElemType *bottom;
  ElemType  *top;
  int stack_size;
}stack_node;
status init_stack(stack_node *S)
{
    S->bottom=(ElemType*)malloc(STACK_MAX_SIZE*sizeof(ElemType));
    if(S->bottom==NULL)
        return ERROR;
    else
    {
        S->top=S->bottom;
        S->stack_size=STACK_MAX_SIZE;
        return OK;
    }
}
status push(stack_node *S,int e)
{   int  *p;
    if(S->top-S->bottom>=STACK_MAX_SIZE)
    {
        p=(ElemType*)realloc(S->bottom,(STACK_MAX_SIZE+increment)*sizeof(ElemType));
        if(p==NULL)
            return ERROR;
        else
        {    S->bottom=p;
            S->top=S->bottom+S->stack_size;
            S->stack_size+=increment;
            *S->top=e;
            S->top++;
            return OK;
        }
    }
        else
        {    *S->top=e;
        S->top++;
        return OK;
        }
    }
status pop(stack_node *S,int *e)
{
    if(S->top==S->bottom)
   
        return ERROR;
        else
        {
            S->top--;
            *e=*S->top;
            return OK;
        }
}
void main()
{
    stack_node S;
    int e;
    int xz=1;
    if(init_stack(&S)!=OK)
        printf("初始化未成功!\n");
    else
        while(xz!=0)
        {
            printf("1.入栈\t2.出栈\t0.结束\n");
            scanf("%d",&xz);
            switch(xz)
            {
            case 1:
                printf("请输入要入栈的数:");
                scanf("%d",&e);
                if(push(&S,e)==OK)
                    printf("入栈成功!\n");
                 else
                     printf("入栈未成功!\n");
                     break;
            case  2:
                if(pop(&S,&e)==OK)
                    printf("出栈的元素为:%d\n",e);
                else
                    printf("栈已为空!\n");
                break;

            case 0:
                printf("谢谢使用,再见!\n");
                break;
            default:
               
                    printf("输入有误,请重新输入!\n");
                    break;
            }
        }
}
搜索更多相关主题的帖子: 分享 交流 include return bottom 
2013-05-11 16:48



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-406827-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.169486 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved