データ構造C言語-シーケンススタックとチェーンスタック

14594 ワード

#include 
#include 

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;

#define MAXSIZE 100
typedef struct
{
    ElemType *base;
    ElemType *top;
    int stacksize;
}SqStack;

status InitStack(SqStack *s)
{
    s->base=(ElemType *)malloc(sizeof(ElemType)*MAXSIZE);
    if(!s->base)
        exit(OVERFLOW);
    s->top=s->base;
    s->stacksize=MAXSIZE;
    return OK;
}

status Push(SqStack *s,ElemType e)
{
    if(s->top-s->base==s->stacksize)
        return ERROR;
    *(s->top)=e;
    s->top++;
    return OK;
}

status Pop(SqStack *s,ElemType *e)
{
    if(s->top==s->base)
        return ERROR;
    s->top--;
    *e=*(s->top);
    return OK;
}

ElemType GetTop(SqStack s)
{
    if(s.top!=s.base)
        return *(s.top-1);
}

//  
typedef struct StackNode
{
    ElemType data;
    struct StackNode *next;
}StackNode,*LinkStack;

status InitStackNode(LinkStack *s)
{
    *s=NULL;
    return OK;
}

status PushNode(LinkStack *s,ElemType e)
{
    //LinkStack r=*s;   r  ??
    StackNode *p=(StackNode *)malloc(sizeof(StackNode));
    p->data=e;
    p->next=*s;
    *s=p;
    return OK;
}

status PopNode(LinkStack *s,ElemType *e)
{
    //LinkStack r=*s;
    if(*s==NULL)
        return ERROR;
    *e=(*s)->data;
    StackNode *temp=*s;
    *s=(*s)->next;
    free(temp);
    return OK;
}

ElemType GetTopNode(LinkStack s)
{
    if(s==NULL)
        return ERROR;
    return s->data;
}
int main()
{
    //   
    /*
    SqStack s;
    InitStack(&s);
    Push(&s,1);
    Push(&s,2);
    Push(&s,3);
    Push(&s,4);
    printf("top of the stack: %d
",GetTop(s)); ElemType a; int num=4,i; for(i=0;i // LinkStack s; InitStack(&s); int i,num=5; for(i=0;i<num;i++) { PushNode(&s,i+1); printf("Push:%d
"
,GetTopNode(s)); } ElemType a; for(i=0;i<num;i++) { PopNode(&s,&a); printf("Pop:%d
"
,a); } return 0; }