栈的建立&操作(C语言)

来源:互联网 发布:mac开机黑屏logo不亮 编辑:程序博客网 时间:2024/06/07 19:30

#include "Stdio.h"
#define StackSize 100                                            /*定义储存空间大小*/
typedef char DataType;   

 

 

 /****************定义栈储存空间结构************/                                         

typedef struct
{
   DataType data[StackSize]; /**/
   int top; /**/

}SqlStack;

 

 

 

 /*****************生成栈*******************/
void Ininital(SqlStack* S)
{
     S->top=-1;
}

 

 

 

 /*****************判空****************/

int IsEmpty(SqlStack* S)
{
    return S->top==-1;
}

 

 

 /***************判满*****************/

int IsFull(SqlStack* S)
{
    return S->top==StackSize-1;
}

 

 

 /**************压栈*****************/

void Push(SqlStack* S,DataType ch)
{
    if(IsFull(S))
    {
        printf("full");
        exit(1);
    }
    S->data[++S->top]=ch;
}

 

 

 /***************弹桟**************/

DataType Pop(SqlStack* S)
{
    if(IsEmpty(S))
    {
        printf("empty");
        exit(1);
    }
    return S->data[S->top--];
}

 

 

 

 /****************取栈顶元素*****************/

DataType Top(SqlStack* S)
{
    if(IsEmpty(S))
    {
        printf("empty");
    }
    return S->data[S->top];
}

 

 

 

 /*************主函数******************/
int main(void)
{
    DataType x,y;
    SqlStack stack;

    Ininital(&stack);

    Push(&stack,'p');
    Push(&stack,'u');

    x=Top(&stack);
    Pop(&stack);

    y=Top(&stack);
    Pop(&stack);
    printf("%c",x);
    printf("%c",y);

    getch();
    return 0;
}

 

 

 

 

 

 

 

 

/*************另一种做法(类表现形式)*********************/

#include "Stdio.h"
#define StackSize 100
typedef char DataType;


typedef struct
{   DataType data[StackSize];
    int top;
    void (*Initial)();
    int (*IsEmpty)();
    int (*IsFull)();
    void (*Push)();
    char (*Pop)();
    char (*Top)();
}SqlStack;

 

void Initial(SqlStack *S)
{
    S->top=-1;
}

int IsEmpty(SqlStack *S)
{
    return S->top==-1;
}

int IsFull(SqlStack *S)
{
    return S->top==StackSize-1;
}

void Push(SqlStack *S,DataType x)
{  
    if(IsFull(S))
    {
        printf("stack is full ,can't input it");
        exit(1);
    }
    S->data[++S->top]=x;
}

DataType Pop(SqlStack *S)
{
    if(IsEmpty(S))
    {
        printf("the stack is empty ,can't output anything");
    }
    return S->data[S->top--];
}
DataType Top(SqlStack *S)
{
    if(IsEmpty(S))
    {
        printf("stack is null");
        exit(1);
    }
    return S->data[S->top];
}

void start(SqlStack* number)
{
    (*number).Initial=Initial;
    (*number).IsEmpty=IsEmpty;
    (*number).IsFull =IsFull ;
    (*number).Pop=Pop        ;
    (*number).Top=Top        ;
    (*number).Push=Push      ;
}
int main(void)
{
    SqlStack S;
    start(&S);

    S.Initial(&S);

    S.Push(&S,'p');
    S.Push(&S,'u');

    printf("%c",S.Top(&S));

    S.Pop(&S);
    printf("%c",S.Top(&S));

    getch();
    return 0;
}

原创粉丝点击