链栈(C语言)

链栈的基本操作

1. 链栈的结构定义

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

2. 链栈的初始化

/*
    @description: 链栈的初始化
    @return:
    @author: sch
 */
bool InitLinkStack(LinkStack &S)
{
    
    
    S = NULL;
    return success;
}

3. 判断链栈是否为空

/*
    @description: 判断链栈是否为空
    @return:
    @author: sch
 */
bool isEmpty(LinkStack &S)
{
    
    
    if(!S)
        return true;
    else return false;
}

4. 向链栈插入新栈顶元素

/*
    @description: 向链栈插入栈顶元素
    @return:
    @author: sch
 */
bool Push(LinkStack &top, ElemType e)
{
    
    
    StackNode* p = (StackNode*) malloc(sizeof(struct StackNode));
    if(!p)
    {
    
    
        free(p);
        return failed;
    }
    p->data = e;
    p->next = top;
    top = p;
    return success;
}

5. 访问栈顶元素

/*
    @description: 访问链栈的栈顶元素
    @return: 若栈为空返回NULL, 反之返回栈顶结点的地址
    @author: sch
 */
StackNode* GetTop(LinkStack& top)
{
    
    
    return top;
}

6. 弹出栈顶元素

/*
    @description: 弹出链栈栈顶元素
    @return:
    @author: sch
 */
bool Pop(LinkStack &top)
{
    
    
    if(!top)return failed;
    StackNode* p = top;
    top = top->next;
    free(p);
    return success;
}

7. 从栈顶开始遍历链栈

/*
    @description: 从栈顶开始遍历链栈
    @return:
    @author: sch
 */
void LinkStackTraverse(LinkStack top)
{
    
    
    StackNode* p = top;
    while(p)
    {
    
    
        printf("%d\n", p->data);
        p = p->next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45830383/article/details/114438220