zoukankan      html  css  js  c++  java
  • 堆栈——数组实现

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <ctime> 
    
    using namespace std;
    
    using ElemType = int;
    const int MAXSIZE = 20;
    
    // 堆栈结构
    class Stack {
    public:
    	ElemType data[MAXSIZE];
    	int top; 
    };
    
    // 初始化堆栈 
    void initStack(Stack &stack, int n)
    {
    	stack.top = -1;
    	srand(time(NULL));
    	while (n--) {
    		stack.top++;
    		stack.data[stack.top] = rand()%100 + 1;
    	}
    }
    
    // 判空 
    bool isEmpty(const Stack &stack)
    {
    	if (stack.top == -1)
    		return true;
    	return false;
    }
    
    // 压栈 
    void push(Stack &stack, ElemType val)
    {
    	if (stack.top == MAXSIZE - 1) {
    		cout << "stack is full...
    ";
    		return;
    	}
    	stack.top++;
    	stack.data[stack.top] = val;
    }
    
    // 出栈 
    void pop(Stack &stack)
    {
    	if (isEmpty(stack)) {
    		cout << "stack is empty...
    ";
    		return;
    	}
    	stack.top--;
    }
    
    // 返回栈顶元素 
    const ElemType& getTop(const Stack &stack)
    {
    	if (isEmpty(stack)) {
    		cout << "stack is empty...
    ";
    	}
    	return stack.data[stack.top];
    }
    
    // 打印 
    void print(const Stack &stack)
    {
    	if (isEmpty(stack)) {
    		cout << "Empty stack...
    ";
    	}
    	int n = stack.top;
    	cout << "从栈顶到栈底的元素依次为:";
    	while (n != -1) {
    		cout << stack.data[n--] << " ";
    	}
    	cout << endl;
    }
    
    int main()
    {
    	Stack stack;
    	initStack(stack, 10); 
    	print(stack);
    	pop(stack);
    	print(stack);
    	push(stack, 100);
    	print(stack);
    	cout << "栈顶元素为:" << getTop(stack) << endl;
    }
    

      

  • 相关阅读:
    lambda函数用法
    Appium基础篇-元素定位
    python生成测试报告
    jmeter 设置中文
    jmeter bin下常用目录
    高效求幂运算
    欧几里德算法(求最大公因数)
    二分查找
    最大子序列和问题
    秋游小记
  • 原文地址:https://www.cnblogs.com/xzxl/p/8643119.html
Copyright © 2011-2022 走看看