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;
    }


  • 相关阅读:
    因特网中和多媒体有关的协议
    进程与线程
    线程模型
    SMP PVP Cluster
    读写者
    回调函数
    环境变量
    堆与栈的区别
    操作系统中的同步、异步、阻塞和非阻塞
    Razor潜入2令人疑惑的LocateOwner方法
  • 原文地址:https://www.cnblogs.com/csnd/p/12897067.html
Copyright © 2011-2022 走看看