线性表堆栈的链表储存C语言代码+详解注释

当用单向链表结构储存堆栈时,top只能位于链表表头,此时插入和删除都很方便,如果top在链表的表尾,那么无法进行删除操作。

1.基本结构

typedef struct SNode *stack;
struct SNode
{
    ElementType Data;
    struct SNode *Next;
};

2.创建空栈

stack gen()
{
    stack s;
    s=(stack)malloc(sizeof(stack));
    s->Next=NULL;
    return s;
}

3.判断是否为空栈

int IsEmpty(stack s)
{
    //判断栈是否为空 ,若为空则返回整数1,否则返回0
    return (s->Next == NULL);
}

4.入栈
此时栈结构是链式储存,用malloc分配内存,无须验满。

void Push (ElementType item,stack s)
{
    stack node;
    node=(stack)malloc(sizeof(stack));
    node->Data=item;
    node->Next=s->Next;
    s->Next=node;
}

5.出栈

int Pop(stack s)
{
    if(IsEmpty(s))
    {
        printf("栈空");
        return NULL;
    } 

    else
    {
        int top;
        stack p;
        top=s->Next->Data;
        p=s->Next;
        s->Next=p->Next;
        free(p);
        return top;     
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45955041/article/details/106968180