zoukankan      html  css  js  c++  java
  • 数据结构 -- 栈的数组实现法

    栈(Stack)是一种线性存储结构,它具有如下特点:

    1. 栈中的数据元素遵守”先进后出"(First In Last Out)的原则,简称FILO结构。
    2. 限定只能在栈顶进行插入和删除操作。

    下面将使用c++实现栈的结构与入栈出栈等操作:

    参考代码:

    #include <cstdio>
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    #define MAXN 100
    #define PUSH_ERROR 0x1
    #define POP_ERROR 0x2
    
    
    struct stack{
    	int arr[MAXN];
    	int top;
    };
    
    //初始化栈结构
    
    void init_stack(struct stack *st){
    	st->top = 0;
    	return;
    }
    
    //入栈
    
    int push(struct stack *st , int val){
    	if (st->top < MAXN)
    	{
    		st->arr[st->top++] = val;
    	}else{
    		return PUSH_ERROR;
    	}
    	return 0;
    }
    
    //出栈
    
    int pop(struct stack *st){
    	if (st->top > 0)
    	{
    		printf("The POP val is %d
    ",st->arr[st->top-1]);
    		st->top--;
    	}else{
    		return POP_ERROR;
    	}
    	return 0;
    
    }
    
    
    //求栈顶元素
    
    int Top(struct stack *st){
    	printf("TOP VAL is %d
    ",st->arr[st->top-1]);
    	return 0;
    }
    
    //求栈的大小
    
    int show(struct stack *st){
    	int count = 0;
    	for (int i = 0 ; i < st->top ; i++)
    	{
    		count++;
    	}
    	return count;
    }
    
    int main(void){
    	struct stack *st1 = (struct stack *)malloc(sizeof(struct stack));
    	init_stack(st1);
    	push(st1,1);
    	push(st1,3);
    	push(st1,2);
    	printf("Count: %d 
    ",show(st1));
    	Top(st1);
    	pop(st1);
    	pop(st1);
    	printf("Count: %d 
    ",show(st1));
    	return 0;
    }


  • 相关阅读:
    add repository(仓库) EntityState状态
    添加 Attribute(属性)和Attribute的用法
    分部视图 Partial View
    MVC架构+ef 添加、删除、查询用户。。。
    首次接触 ef
    了解ASP.NET MVC的基本架构
    C# SqlParameter SqlCommand
    mysql命令行导出导入,附加数据库
    py03_变量
    py02_操作系统
  • 原文地址:https://www.cnblogs.com/csnd/p/12897067.html
Copyright © 2011-2022 走看看