C++数据结构与算法堆栈学习笔记(使用类模板)

2021/4/14 20:31:04

本文主要是介绍C++数据结构与算法堆栈学习笔记(使用类模板),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

基础介绍

数据结构

1. 软件 = 程序 + 文档

程序 = 数据结构 + 算法

2. 对于一个数据结构来讲,需要做到增删减查四个基本功能。

堆栈

堆栈是一种数据结构。堆栈都是一种数据项按序排列的数据结构,只能在一端(称为栈顶(top))对数据项进行插入和删除。

堆栈就像一个圆柱体的硬币盒(只开一边口),每次只能从顶部操作,后进先出,每次只能取得最顶部的一枚硬币。

模板类

在定义类之前,使用template<class Item>获得一个模板

(item处可以自己命名,用于代替类型的名称)
——————————————————代码实现———————————————————
#include<iostream>
enum Error_code{underflow,overflow,success}; 
		//枚举元素来表示函数返回值
using namespace std;
template<class Item> //模板

class Stack{
    private:
        enum {MAX=50};
        Item items[MAX];
        int count;

    public:
        Stack();  //初始化
        bool isempty() const;   //堆栈是否为空
        bool isfull() const;    //堆栈是否满
        Error_code push(const Item& item); //将item压入堆栈内
        Error_code pop();                  //弹出栈顶元素
        Error_code Top(Item&item);         //将栈顶元素赋值给item(不破坏内部结构)
        void clear();                     //清空栈
};
template<class Item>    //每次定义前都要使用模板代替不确定的类型
Stack<Item>::Stack() { 
        count = 0;
        for (int i = 0; i < MAX; i++)
            items[i] = 0;
     }
template<class Item>
bool Stack<Item>::isempty() const {
    if (count != 0)
      return false;
    else
      return true;
  }
template<class Item>
bool Stack<Item>::isfull() const {
    if (count != MAX)
      return false;
    else
      return true;
  }
template<class Item>
Error_code Stack<Item>::push(const Item& item) {
    if (count < MAX) {
      items[count++] = item;
      return success;
    } else
      return overflow;
  }
template<class Item>
Error_code Stack<Item>::pop() {
    if (count > 0) {
      items[count] = 0;
      --count;
      return success;
    } else
      return underflow;

  }
template<class Item>
Error_code Stack<Item>::Top(Item&item) { 
    if (count!=0){
      item=items[count-1];
      return success;
    }
    return underflow;
  }
template<class Item>
void Stack<Item>::clear() {
    while (count > 0){
      pop();
    }
  }
//试试看
int main(){
    int nums;
    Stack<int> testStack;
    for (int i =1;i<=5;i++){
        testStack.push(i);
    }
    for (int i =1;i<=5;i++){
        testStack.Top(nums);
        cout<<nums<<" ";
        testStack.pop();
    }
    return 0;
}```


这篇关于C++数据结构与算法堆栈学习笔记(使用类模板)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程