数据结构之顺序栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37667021/article/details/78088660


/*此顺序栈保存的值字符,若要保存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




猜你喜欢

转载自blog.csdn.net/m0_37667021/article/details/78088660