Stack(栈)v1.0

来源:互联网 发布:selfiecity软件下载 编辑:程序博客网 时间:2024/05/23 01:19

栈的实现确实不难,但依旧很有趣,也很值得学习。

条目:

1.使用了typedef

2.实现基本功能

stack.h文件

const int maxstack = 10;// small value for testing#include <string>typedef int Stack_type;typedef char* Error_code;class Stack{public:Stack();bool empty()const;Error_code pop();Error_code push(const Stack_type &item);Error_code top(Stack_type &item)const;private:int count;Stack_type entry[maxstack];}; 

stack.cpp文件

#include "stack.h"Stack::Stack(){count = 0;}bool Stack::empty()const{return count == 0;}Error_code Stack::pop(){Error_code outcome = "success";if (count == 0)outcome = "underflow";else count --;return outcome;}Error_code Stack::push(const Stack_type &item){Error_code outcome = "success";if (count == maxstack)outcome = "overflow";else entry[count++] = item;return outcome;}Error_code Stack::top(Stack_type &item)const{Error_code outcome = "success";if (count == 0) outcome = "underflow";else item = entry[count - 1];return outcome;  }

附送测试的main.cpp 

#include "stack.h"#include <iostream>using namespace std;int main(){Stack s;cout << s.empty()<< endl;cout << s.pop()<< endl;cout << s.push(123)<< endl;cout << s.empty()<< endl;Stack_type item;cout << s.top(item)<< endl;cout << item<< endl;}