C语言数据结构(6)--链栈

1. 顺序栈的缺点

很显然,顺序栈使用数组作为存储结构,面临存储空间有限的限制。

可以将链表作为存储结构,拓展存储空间,即为链栈。

2. 代码实现

/*
* 链栈
* 作者:熊猫大大
* 时间:2019-09-25
*/
#include<stdio.h>

//链栈的节点结构体
typedef struct {
    int data;//保存节点数据
    struct Node *next;//指向下一个节点
}Node;


// 显示所有元素(方便测试)
void printStack(Node *head)
{
    int i;
    printf("=====================栈内所有元素:\n");
    Node* p = head;//定义一个指针首先指向头结点
    while (p->next != NULL)
    {
        p = p->next;
        printf("%d ", p->data);
    }
    printf("\n=====================\n");
}

// 入栈(在链表头部插入元素)
int push(Node *head,int input)
{
    //入栈的新节点
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = input;
    //将新节点放到开头位置
    temp->next = head->next;
    head->next = temp;
    return 1;
}

// 出栈(在链表头部弹出元素)
int pop(Node *head, int* result)
{
    // 栈为空
    if (head->next == NULL) {
        return 0;// 表示失败
    }
    Node* p = head->next;
    // 获取栈顶数据
    *result = p->data;
    // 删除中间元素
    head->next = p->next;
    free(p);
    return 1;//1表示成功
}

// 入口
int main()
{
    // 定义空栈
    Node head;
    head.data = 0;
    head.next = NULL;
    // 展示
    printStack(&head);
    // 入栈
    push(&head,1);
    push(&head, 2);
    push(&head, 3);
    push(&head, 4);
    printStack(&head);
    // 出栈
    int result = 0;
    pop(&head,&result);
    printf("OUT:%d\n", result);
    pop(&head, &result);
    printf("OUT:%d\n", result);
    pop(&head, &result);
    printf("OUT:%d\n", result);
    pop(&head, &result);
    printf("OUT:%d\n", result);
    printStack(&head);
    return 1;
}


上一篇:C语言数据结构(10)--串的改进模式匹配算法(KMP)


下一篇:Mysql 密码忘记如何修改密码