数据结构之顺序栈


/*此顺序栈保存的值字符,若要保存int可对elemtye作修改*/

#include<stdio.h>
#include<string.h>
#include<string>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define stack_init_size 100
#define stackIncrement 10
typedef int status;
typedef char Elemtype;
typedef struct mytack
{
    Elemtype *base;
    Elemtype *top;
    int stackSize;
} Stack;

status initStack(Stack &s)
{
    s.base=(Elemtype*)malloc(stack_init_size*sizeof(Elemtype));
    if(s.base==NULL)return ERROR;
    s.top=s.base;
    s.stackSize=stack_init_size;
    return OK;
}
status push(Stack &s,Elemtype elem)
{
    if(s.top-s.base>=s.stackSize)
    {
        s.base=(Elemtype *)realloc(s.base,(s.stackSize+stackIncrement)*sizeof(Elemtype));
        if(s.base==NULL)return ERROR;
        s.top=s.base+s.stackSize;
        s.stackSize=s.stackSize+stackIncrement;
    }
    *s.top=elem;
    s.top++;
    return OK;
}
status pop(Stack &s)
{
    if(s.base==s.top)return ERROR;
    s.top--;
    return OK;
}
status traverse(Stack s)
{
    while(s.top!=s.base)
    {
        printf("%c",*(s.top-1));
        s.top--;
    }
    printf("\n");
    return OK;
}
status clearStack(Stack &s)
{
    s.top=s.base;
    return OK;
}
int gettop(Stack s)
{
    if(s.top==s.base)return ERROR;
    return *(s.top-1);
}
int  getsize(Stack s)
{
    int cnt=s.top-s.base;
    return cnt;
}
int stackEmpty(Stack s)
{
    if(s.base==s.top)return 1;
    else return 0;
}
int main()
{
    int i,j,tmp;
    char ch;
    Stack mystack;
    initStack(mystack);
    char s[1000];

    while(scanf("%s",s)!=EOF)
    {
        getchar();
        for(i=0; i<strlen(s); i++)
            push(mystack,s[i]);
        traverse(mystack);
        // printf("\n");
        clearStack(mystack);
        traverse(mystack);
        while(!stackEmpty(mystack))pop(mystack);
    }
    return 0;
}
//123456
//abcde




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值