栈——链栈(不带头结点)的定义以及基本操作 超详细!

#include
#include
#include

//结构体定义
typedef struct linknode
{
    int data;
    struct linknode* next;
}linknode, *linkstack;

//初始化链栈
void initialize_stack(linkstack* s)
{
    (*s) = NULL;
}

//进栈(增)
void push(linkstack* s, int x)
{
    linknode* p = (linknode*)malloc(sizeof(linknode));
    p->next = NULL;

    p->data = x;
    p->next = (*s);
    (*s) = p;

    return;
}

//出栈(删)
void pop(linkstack* s)
{
    printf("the element deleted is: %d \n", (*s)->data);

    linknode* p;
    p = (*s);
    (*s) = (*s)->next;
    free(p);
    return;
}

//读栈顶元素(查)
void top_stack(linkstack s)
{
    if(s == NULL)
    {
        printf("the top:there is not element in it.\n");
        return;
    }
    else
    {
        printf("the top of the stack is:%d\n", s->data);
        return;
    }
}

//判空
void empty_stack(linkstack s)
{
    if(s == NULL)
    {
        printf("the stack is empty.\n");
        return;
    }
    else
    {
        printf("the stack is not empty.\n");
        return;
    }

}

//打印链栈
void print_stack(linkstack s)
{
    if(s == NULL)
    {
        printf("print stack:there is not element in it.\n");
        return;
    }
    else
    {
        printf("the elements of this stack:");
        while(s != NULL)
        {
            printf("%d ", s->data);
            s = s->next;
        }
        printf("\n");
        return;
    }
}

int main()
{
    linkstack s;
    initialize_stack(&s);
    push(&s, 1);
    push(&s, 2);
    push(&s, 5);
    print_stack(s);

    pop(&s);
    pop(&s);
    pop(&s);
    print_stack(s);

    top_stack(s);

    empty_stack(s);

    return 0;
}

如有错误还请指正~

你可能感兴趣的:(数据结构,考研)