链式栈


#include 
#include 
typedef struct Node
{
    int val;
    struct Node *next;
}Node,*PNode;
typedef struct Stack
{
    struct Node *top;
    struct Node *bottom;
}SNode,*SpNode;
void init(SpNode stack)//初始化栈区
{
    PNode a;
    a=(struct Node *)malloc(sizeof(Node));
    stack->top=stack->bottom=NULL;
    stack->top=stack->bottom=a;
    if (stack->top!=NULL)
    {
        printf("Apply successful!\n");//申请空间成功
        stack->bottom->next=NULL;
    }
    else
    {
        printf("Apply fail\n");//申请空间失败
    }
}
void push(SpNode stack,int val)//压栈
{
    PNode a;
    a=(struct Node *)malloc(sizeof(Node));
    a->val=val;
    a->next=stack->top;
    stack->top=a;
    return ;
}
void traverse(SpNode stack)//遍历栈
{
    PNode front;
    front=stack->top;
    while (front!=stack->bottom)
    {
        printf("%d ",front->val);
        front=front->next;
    }
    printf("\n");
    return;
}
int empty(SpNode stack)//判断是否为空栈
{
    if (stack->top==stack->bottom)
        return 1;
    return 0;
}
void pop(SpNode stack,int *val)//出栈
{
    if (empty(stack))
    {
        printf("Empty stack\n");
        return;
    }
    PNode a;
    a=stack->top;
    stack->top=stack->top->next;
    *val=a->val;
    free(a);
    return;
}
void clear(SpNode stack)
{
    PNode q,r;
    if(empty(stack))
    {
        return;
    }
    q=stack->top;
    while(q!=stack->bottom)
    {
        r=q->next;
        q->val=0;
        q=r;
    }
    return;
}
int main()
{
    SNode stack;
    int val;
    init(&stack);
    push(&stack,1);
    push(&stack,2);
    push(&stack,3);
    push(&stack,4);
    push(&stack,5);
    push(&stack,6);
    traverse(&stack);
    pop(&stack,&val);
    printf("%d successful push!\n",val);
    traverse(&stack);
    clear(&stack);//清空栈区
    traverse(&stack);
    return 0;
}

相关