算法导论第10章基本数据结构10.1栈
2015-02-11 15:23
519 查看
/* * IA_10.1_stack.h * * Created on: Feb 13, 2015 * Author: sunyj */ #ifndef IA_10_1_STACK_H_ #define IA_10_1_STACK_H_ #include <cstdint> // STACK-EMPTY(S) // if S.top == 0 // return TRUE // else return FALSE // PUSH(S, x) // S.top = S.top + 1 // S[S.top] = x // POP(S) // if STACK-EMPTY // error "under flow" // else S.top = S.top - 1 // return S[S.top + 1] template <class Type> class stack { public: // length is a const reference, be careful, if n is not a const reference, length would be attached to // a local variable n, see the constructor commented below stack(const int64_t& n) : top(-1), length(n) { data = new Type (); } /* stack(int64_t const n) : top(-1), length(n) { data = new int64_t (); } */ bool empty() { return -1 == top; } int64_t push (Type x) { if (length == top + 1) { std::cout << "stack is full, push failed." << std::endl; return -1 ; } data[++top] = x; return 0 ; } int64_t pop(Type& x) { if(empty()) { std::cout << "stack is empty, pop failed." << std::endl; return -1; } x = data[top--]; return 0; } void PrintStack() { if (empty()) { return; } for (int64_t i = 0; i < top + 1; i++) { std::cout << data[i] << " "; } std::cout << std::endl; } private: Type* data; int64_t top; // point to the top element of the stack const int64_t& length; }; #endif /* IA_10_1_STACK_H_ */
/* * IA_10.1_stack.cpp * * Created on: Feb 11, 2015 * Author: sunyj */ #include <iostream> #include <stdio.h> #include "IA_10.1_stack.h" int main() { stack<int64_t> st(3); std::cout << st.empty() << std::endl; int64_t e; if (0 == st.pop(e)) { std::cout << e << std::endl; } st.PrintStack(); st.push(1); st.push(5); st.push(3); st.push(4); st.PrintStack(); if (0 == st.pop(e)) { std::cout << e << std::endl; } st.PrintStack(); return 0; }
相关文章推荐
- 链表_第10章_基本数据结构_算法导论
- 栈与队列_第10章_基本数据结构_算法导论
- 【算法导论】学习笔记——第10章 基本数据结构
- 有根树的表示_第10章_基本数据结构_算法导论
- 算法导论 第三部分——基本数据结构——栈、队列、链表、散列表
- 基本数据结构(算法导论)与python
- 算法导论第10章-基本数据结构-10.1栈和队列
- 算法导论笔记:10基本数据结构(番外)
- 算法导论 第四部分——基本数据结构——第15章:动态规划:背包问题
- 基本数据结构(算法导论)与python
- 基本数据结构(2)——算法导论(12)
- 算法导论——第七章——基本数据结构
- 基本数据结构(算法导论)与python
- 基本数据结构(算法导论)与python
- 算法导论10(基本数据结构)
- MIT:算法导论——7.1.基本数据结构_栈、队列、链表、有根树
- 算法导论-5.基本数据结构
- 基本数据结构(算法导论)与python
- 算法导论学习笔记(16)——图的基本算法
- 《妙趣横生的算法》第10章 算法设计与数据结构面试精粹之常见的算法设计题10-1