Demo entry 6749473

stackfunction

   

Submitted by anonymous on Jun 13, 2018 at 05:30
Language: C. Code size: 1.6 kB.

#define OVERFLOW -2
typedef struct SNode{
    char data;
    struct SNode *next;
}SNode, Linkstack;
Linkstack *InitStack();
void DestroyStack(Linkstack *S);
int StackEmpty(Linkstack *S);
void Push(Linkstack *S,char e);
char Pop(Linkstack *S);
char GetTop(Linkstack *S);
void TraverseStack(Linkstack *S);
Linkstack *InitStack(){//构造一个空栈S,并返回其头结点地址
    Linkstack *S;
    S=(Linkstack *)malloc(1*sizeof(Linkstack));
    if(!S)exit(OVERFLOW);
    S->next=NULL;
    return S;
}
void DestroyStack(Linkstack *S){   //销毁栈S
    Linkstack *p,*q;//p用于删除结点,q用于遍历
    q=S;
    while(q->next!=NULL){
        p=q;
        q=q->next;
        free(p);
    }
    free(q);
}
int StackEmpty(Linkstack *S){  //若栈为空栈则返回1,否则返回0
    if(S->next==NULL)//判断头结点的next是否为null即可
        return 1;
    else return 0;
}
void Push(Linkstack *S,char e){//插入新元素e作为栈顶元素
    SNode *p;
    p=(SNode *)malloc(1*sizeof(SNode));
    if(!p) exit(OVERFLOW);//用p申请新结点并赋值
    p->data=e;
    p->next=S->next;
    S->next=p;//将p接在头结点后
}
char Pop(Linkstack *S){//若栈不空则删除栈顶元素并返回删除的元素值
    SNode *p;//p用来删除结点
    char e;//e用来记录并返回头结点数据
    if(StackEmpty(S)) return 0;//栈为空时返回0
    p=S->next;
    e=p->data;
    S->next=p->next;
    free(p);
    return e;
}
char GetTop(Linkstack *S){//若栈不空则返回S的栈顶元素
    char e;
    if(StackEmpty(S)) return 0;//栈为空时返回0
    e=S->next->data;
    return e;
}
void TraverseStack(Linkstack *S){//遍历栈各结点并从头到尾输出
    SNode *p;
    p=S->next;
    while(p!=NULL){
        printf("%c\n",p->data);
        p=p->next;
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).