链栈

作者: northw1nd | 来源:发表于2018-11-13 12:16 被阅读0次

    参考书籍:《大话数据结构》
    环境:VS2017

    #include<stdio.h>
    #include<stdlib.h>
    
    #define OK 1
    #define ERROR 0
    #define TRUE 1
    #define FALSE 0
    #define MAXSIZE 20
    
    typedef int Status;
    typedef int SElemType;
    
    typedef struct StackNode
    {
        SElemType data;
        struct StackNode *next;
    }StackNode,*LinkStackPtr;
    
    typedef struct
    {
        LinkStackPtr top;
        int count;
    }LinkStack;
    
    Status visit(SElemType e)
    {
        printf("%d ", e);
        return OK;
    }
    
    Status InitStack(LinkStack *S)
    {
        S->top = (LinkStackPtr)malloc(sizeof(StackNode));
        if (!(S->top))
            return ERROR;
        S->top = NULL;
        S->count = 0;
        return OK;
    }
    
    Status StackEmpty(LinkStack S)
    {
        if (S.count == 0)
            return TRUE;
        else
            return FALSE;
    }
    
    Status ClearStack(LinkStack *S)
    {
        LinkStackPtr p, q;
        p = S->top;
        while (p)
        {
            q = p->next;
            free(p);
            p = q;
        }
        return OK;
    }
    
    int StackLength(LinkStack S)
    {
        return S.count;
    }
    
    Status GetTop(LinkStack S, SElemType *e)
    {
        *e = S.top->data;
        return OK;
    }
    
    Status Push(LinkStack *S, SElemType e)
    {
        LinkStackPtr p = (LinkStackPtr)malloc(sizeof(StackNode));
        p->data = e;
        p->next = S->top;
        S->top = p;
        S->count++;
        return OK;
    }
    
    Status Pop(LinkStack *S, SElemType *e)
    {
        LinkStackPtr p = (LinkStackPtr)malloc(sizeof(StackNode));
        *e = S->top->data;
        p = S->top;
        S->top = S->top->next;
        free(p);
        S->count--;
        return OK;
    }
    
    Status StackTraverse(LinkStack S)
    {
        int i = 0;
        LinkStackPtr p = S.top;
        while (p)
        {
            visit(p->data);
            p = p->next;
        }
        printf("\n");
        return OK;
    }
    
    int main()
    {
        int j;
        LinkStack s;
        int e;
        if (InitStack(&s) == OK)
            for (j = 1; j <= 10; j++)
                Push(&s, j);
        printf("栈中元素依次为:");
        StackTraverse(s);
        Pop(&s, &e);
        printf("弹出的栈顶元素 e=%d\n", e);
        printf("栈空否:%d(1:空 0:否)\n", StackEmpty(s));
        GetTop(s, &e);
        printf("栈顶元素 e=%d 栈的长度为%d\n", e, StackLength(s));
        ClearStack(&s);
        printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(s));
        
        system("pause");
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:链栈

          本文链接:https://www.haomeiwen.com/subject/riwkfqtx.html