链表栈

链表栈

 链表栈是一种受到限制的单向链表,数据只能从栈顶压入(相当于头插),先进后出原则,遵从栈的逻辑。

构造链表栈

 使用结构体来构造链表栈,其中data用来存储数据,*next用来指向下一个节点。

typedef struct listStack{

    int data;
    struct listStack *next;

}my_list_stack, *p_list_stack;

新建节点

 定义一个节点,并分配节点,最后返回它的地址。

p_list_stack new_node()
{
    p_list_stack new = calloc(1, sizeof(my_list_stack));
    if(NULL == new)
        return NULL;

    new->next = NULL;

    return new;
}

压栈

int input_msg(char * msg)
{
    // 让用户输入新的数据
    int num ;
    printf("%s:" , msg);
    scanf("%d" , &num);
    while(getchar() != '
');

    return num;
}

p_list_stack push_stack(p_list_stack list_stack)
{
    p_list_stack new = new_node();
    if(NULL == new)
        return NULL;

    new->data = input_msg("Please enter the stack data");

    new->next  = list_stack;
    list_stack = new;

    return list_stack;
}

出栈

int pop_stack(p_list_stack *list_stack)
{
    if (NULL == *list_stack)
    {
        printf("The stack failed. The stack is empty
");
        return -1;
    }

    p_list_stack tmp_pos = (*list_stack);
    (*list_stack) = tmp_pos->next;
     tmp_pos->next = NULL ;

    return tmp_pos->data;
}

测试函数

int test()
{
    p_list_stack list_stack = NULL;

    list_stack = push_stack(list_stack);
    list_stack = push_stack(list_stack);
    list_stack = push_stack(list_stack);
    list_stack = push_stack(list_stack);
    list_stack = push_stack(list_stack);

    for (int i = 0; i < 5; i++)
    {
        int data = pop_stack(&list_stack);
        printf("data:%d
", data);
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/ding-ding-light/p/14117429.html