数据结构_栈_C语言



在这里插入图片描述

一、存储结构

typedef struct Node {
    int data;
    struct Node *next;
} Node;

二、函数列表

Node *initStack()初始化栈
void push(Node *L, int data)进栈,把元素data压入栈
int pop(Node *L) 出栈
int isEmpty(Node *L)判断栈是否为空
void printStack(Node *stack)遍历栈,打印每一个元素

三、完整代码

#include <stdio.h>
#include <stdlib.h>

/**
 * define struct of stack
 */
typedef struct Node {
    int data;
    struct Node *next;
} Node;

/**
 * init stack
 * @return the head pointer of stack
 */
Node *initStack() {
    Node *L = (Node *)malloc(sizeof(Node));
    L->data = 0;
    L->next = NULL;
    return L;
}

/**
 * push item in stack
 * @param L the head pointer of stack
 * @param data the data you want to push
 */
void push(Node *L, int data) {
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = data;
    node->next = L->next;
    L->next = node;
    L->data++;
}

/**
 * pop item in stack
 * @param L the head pointer of stack
 * @return data
 */
int pop(Node *L) {
    if (L->data == 0) {
        return 0;
    } else {
        Node *node = L->next;
        int data = node->data;
        L->next = node->next;
        free(node);
        L->data--;
        return data;
    }
}

/**
 * judge stack is or not empty
 * @param L the head pointer of stack
 * @return empty flag
 */
int isEmpty(Node *L) {
    if (L->data == 0 || L->next == NULL) {
        return 1;
    } else {
        return 0;
    }
}

/**
 * print all items in stack
 * @param stack the head pointer of stack
 */
void printStack(Node *stack) {
    Node *node = stack->next;
    while (node) {
        printf("%d -> ", node->data);
        node = node->next;
    }
    printf("NULL\n");
}

/**
 * main function
 * @return null
 */
int main() {
    Node *stack = initStack();
    push(stack, 1);
    push(stack, 2);
    push(stack, 3);
    push(stack, 4);
    printStack(stack);
    printf("pop = %d\n", pop(stack));
    printStack(stack);
}


执行结果:
在这里插入图片描述


个人学习笔记,如有错误,还请指正

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值