美文网首页
5、模拟栈操作

5、模拟栈操作

作者: 十二月_9d09 | 来源:发表于2019-07-28 07:36 被阅读0次
 /**
 *  栈是一种数据结构,特点:先进后出
 *  练习:使用全局变量模拟栈的操作
 */
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
//保护全局变量:在全局变量前加static后,这个全局变量就只能在本文件中使用
static int data[1024];//栈最多能保存1024个数据
static int count = 0;//目前已经放了多少个数(相当于栈顶位置)

//数据入栈 push
void push(int x){
    assert(!full());//防止数组越界
    data[count++] = x;
}
//数据出栈 pop
int pop(){
    assert(!empty());
    return data[--count];
}
//查看栈顶元素 top
int top(){
    assert(!empty());
    return data[count-1];
}

//查询栈满 full
bool full() {
    if(count >= 1024) {
        return 1;
    }
     return 0; 
}

//查询栈空 empty
bool empty() {
    if(count <= 0) {
        return 1;
    }
    return 0;
}

int main(){
    //入栈
    for (int i = 1; i <= 10; i++) {
        push(i);
    }
  
    //出栈
    while(!empty()){
        printf("%d ", top()); //栈顶元素
        pop(); //出栈
    }
    printf("\n");
    
    return 0;
}

相关文章

  • 5、模拟栈操作

  • 算法-栈和队列算法总结

    栈和队列算法总结 1 模拟 1.1 使用栈实现队列 1.2 使用队列实现栈 2 栈的应用 2.1 栈操作 2.2 ...

  • iOS_Swift一些常见的算法

    1、A和B交换值 2、求最大公约数 3、模拟栈操作(一种先进后出的数据结构) 练习:使用全局变量模拟栈的操作 4、...

  • python 中的栈

    python 是没有栈的,我们可以模拟一个栈 stack通常的操作: Stack() 建立一个空的栈对象push(...

  • 用两个队列实现栈

    题目: 用两个队列模拟实现栈的push以及pop操作。 解法:

  • 队列与栈相关题目

    使用栈模拟队列操作题目链接: https://leetcode.com/problems/implement-qu...

  • 42-模拟栈操作

    ``` stack = [] def push_it(): data =input('数据: ').strip()...

  • Java 二级复习整理

    二级考试模拟卷11、栈按先进后出的原则,所以入栈最早的最后出栈;数据的插入删除都是在栈顶进行操作。所以栈顶元素最后...

  • js栈的操作

    js模拟栈操作,输入两个数组,一个数组作为元素入栈顺序,另一个数组为出栈顺序,若出栈顺序符合入栈规则返回true

  • 面试题9:用两个栈实现队列

    题意:请用栈实现一个队列,支持如下四种操作:pop,push,peek,empty 算法:模拟 思路:一个栈存放数...

网友评论

      本文标题:5、模拟栈操作

      本文链接:https://www.haomeiwen.com/subject/xbqbkctx.html