0
点赞
收藏
分享

微信扫一扫

数据结构学习之栈

琛彤麻麻 2022-04-23 阅读 64

数组加循环>>栈

栈先入后出(FILO)例子弹 先压进的后打出

栈里面的数据可以是任意数据类型

入栈 向里面放数据

出栈 将数据从栈里取出

栈只有入栈和出栈的操作

并且只能操作最顶层的数据

/*
思路:
@创建一个容器 即数组
@放数据: 栈指针指向下一个位置 此时指向的数据为空 top++
@取数据: 将指针指向之前放入的数据 即--top
@检测数据是否为空:为空则结束取数据 

简洁版:

//数据结构:栈
#include<stdio.h>
​
char stack[512];//存放栈的数据
int top = 0;    //指向栈顶的指针
​
void push(char c);
char pop(void);
int is_empty(void);
​
int main(void) {
    push('a');
    push('b');
    while (!is_empty()) {
        putchar(pop());
    }
    return 0;
}
​
//入栈操作
void push(char c) {
    stack[top++] = c;
}
​
//出栈操作
int pop(void) {
    return stack[--top];
}
​
//检测栈是否为空
int is_empty(void) {
    return top == 0;
}

部分注释版本:

//数据结构:栈
#include<stdio.h>
​
char stack[512];//存放栈的数据
int top = 0;        //指向栈顶的指针
​
void push(char c);
char pop(void);
int is_empty(void);
​
int main(void) {
    push('a');
    push('b');
    while (!is_empty()) {  //一直检测栈是否为空 为空则退出  is_empty() == 0与!is_empty()作用相同       
        putchar(pop());
    }
    return 0;
}
​
//入栈操作
void push(char c) {
    //存放数据后指向下一个位置 top++是先使用top 使用完++
    stack[top++] = c;
}
​
//出栈操作
char pop(void) {
    //取出数据指向前一个数据 --top是先减一在使用数据
    return stack[--top];
}
​
//检测栈是否为空
int is_empty(void) {
    //top为零返回真 不为零则为假 真即为空,假即为不空
    return top == 0;
}

全注释版本:方便复习

//数据结构:栈
#include<stdio.h>
​
char stack[512];//存放栈的数据
int top = 0;        //指向栈顶的指针
​
void push(char c);
int pop(void);
int is_empty(void);
​
int main(void) {
    push('a');//放字符a
    push('b');//放字符b
    while (!is_empty()) { //一直检测栈是否为空 为空则退出is_empty() == 0与!is_empty()作用相同
        putchar(pop());//将栈中的数据打印
    }
    return 0;
}
​
//入栈操作
void push(char c) {
    //存放数据后指向下一个位置 top++是先使用top 使用完++
    stack[top++] = c;
}
​
//出栈操作
char pop(void) {
    //取出数据指向前一个数据 --top是先减一在使用数据
    return stack[--top];
}
​
//检测栈是否为空
int is_empty(void) {
    /*  if (top == 0) {
            return 1;   //返回为真
        }
        if (top == 0) {
            return 0;   //返回为假
        }
    */
    //top为零返回真 不为零则为假 真即为空,假即为不空
    return top == 0;
}
举报

相关推荐

0 条评论