顺序栈
来源:互联网 发布:知乎钓鱼岛问题 编辑:程序博客网 时间:2024/06/06 07:06
1、C++版的顺序栈
/***********************//***** seqStack.h ****//***********************/#ifndef _SEQSTACK_H#define _SEQSTACK_Htemplate <class T>class SeqStack{ public: SeqStack(int capacity = 15); ~SeqStack(); void ChangeCapacity(T* &st, int oldCapacity, int newCapacity); bool IsEmpty() const; T& Top() const; void Push(const T& item); T Pop(); private: T *stack; int capacity; int top;};template <class T>SeqStack<T>::SeqStack(int stackCapacity):capacity(stackCapacity){ if (capacity < 1) throw "Stack capacity must be > 0"; stack = new T[capacity]; top = -1;}template <class T>SeqStack<T>::~SeqStack(){ delete[] stack;}template <class T>void SeqStack<T>::ChangeCapacity(T* &st, int oldCapacity, int newCapacity){ if (newCapacity < 0) throw "Realloc storge cannot < 0"; T *temp = new T[newCapacity]; int number = std::min(oldCapacity, newCapacity); std::copy(st, st + number, temp); delete[] st; st = temp; capacity = newCapacity;}template <class T>bool SeqStack<T>::IsEmpty() const{ return (top == -1);}template <class T>inline T& SeqStack<T>::Top() const{ if (IsEmpty()) throw "Stack is empty!"; return stack[top];}template <class T>void SeqStack<T>::Push(const T& item){ if (top == capacity-1){ ChangeCapacity(stack, capacity, 2*capacity); } stack[++top] = item;}template <class T>T SeqStack<T>::Pop(){ if (IsEmpty()) throw "Stack is empty!"; return stack[top--];}#endif
/***********************//***** main.cpp ****//***********************/#include <iostream>#include "seqStack.h"using namespace std;int main(int argc, const char *argv[]){ SeqStack<int> st; int i; if (st.IsEmpty()) cout << "Stack is empty!" << endl; cout << "Push data in..." << endl; for (i = 0; i < 30; i++){ st.Push(i); cout << st.Top() << " "; } cout << endl; cout << "Top of stack" << endl; cout << st.Top() << endl; cout << "Pop data out..." << endl; for (i = 0; i < 30; i++) cout << st.Pop() << " "; cout << endl; return 0;}
阅读全文
0 0
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- 顺序栈
- tf.nn.l2_loss
- CHILDBIRTH TRADITIONS AROUND THE WORLD: CHINA
- 获取android sd卡中某个文件夹下的所有图片
- ssh框架搭建完成后配置
- loadrunner 压力测试 平均响应时间20秒 100用户并发 jquery.easyui.min.js 和jquery.js占用时间最长
- 顺序栈
- go语言入门
- 把数组排成最小的数
- 流行编程语言的详细对比(8)--容器类
- SAP-MM-PA精解分析系列之供应商(02)-账户组解析
- 【POJ 1724】Roads (限制最短路)
- jq 创建节点
- java.lang.String和java.util.Clob互相转换
- 设计模式之代理模式