【数据结构】栈的应用--行编辑程序(c++)
2015-06-01 14:35
597 查看
头文件:
主函数:
![](http://img.blog.csdn.net/20150601143636440?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
#pragma once #include <iostream> #include <assert.h> using namespace std; template<class Type> class SeqStack { public: SeqStack(size_t sz = INIT_SZ); ~SeqStack(); public: bool empty()const; bool full()const; void show()const; bool push(const Type &x); bool pop(); void gettop(Type &x); int length()const; void clear(); void destory(); void quit_system(Type &x); private: enum{ INIT_SZ = 64 }; Type *base; int capacity; int top; }; template<class Type> SeqStack<Type>::SeqStack(size_t sz = INIT_SZ) { capacity = sz > INIT_SZ ? sz : INIT_SZ; base = new Type[capacity]; assert(base != NULL); top = 0; } template<class Type> SeqStack<Type>::~SeqStack() { destory(); } // 判断栈是否满了 template<class Type> bool SeqStack<Type>::full()const { return (top >= capacity); } // 判断是否为空栈 template<class Type> bool SeqStack<Type>::empty()const { return (top == 0); } // 显示 template<class Type> void SeqStack<Type>::show()const { if (top == 0) { cout << "the stack is empty!" << endl; return; } for (int i = top - 1; i >= 0; --i) { cout << base[i] << endl; } } // 入栈 template<class Type> bool SeqStack<Type>::push(const Type &x) { if (full()) { cout << "the stack is full,can not enter!" << endl; return false; } else { base[top] = x; top++; return true; } } // 出栈 template<class Type> bool SeqStack<Type>::pop() { if (empty()) { cout << "the stack is empty,can not pop!" << endl; return false; } else { top--; return true; } } // 获得栈顶元素 template<class Type> void SeqStack<Type>::gettop(Type &x) { x = base[top - 1]; } // 求栈长度 template<class Type> int SeqStack<Type>::length()const { return top; } // 清空栈 template<class Type> void SeqStack<Type>::clear() { top = 0; } // 摧毁栈 template<class Type> void SeqStack<Type>::destory() { delete[]base; base = NULL; capacity = top = 0; } // 退出系统 template<class Type> void SeqStack<Type>::quit_system(Type &x) { x = 0; }
主函数:
#include "Edlin.h" int main() { SeqStack<char> mystack; char ch; cout << "please enter:" << endl; cout << "* @:delete all $:delete one *" << endl; while ((ch = getchar()) != EOF) { switch (ch) { case '@': mystack.clear(); cout << "please enter:" << endl; break; case '$': mystack.pop(); break; default: mystack.push(ch); break; } } mystack.show(); return 0; }
相关文章推荐
- 【数据结构】栈的应用--数制转换(c++)
- COJ983 WZJ的数据结构(负十七)
- 折半查找法的递归和非递归形式
- 图的邻接表存储和基本操作
- 图的数组(邻接矩阵)存储结构和基本操作
- 线性单链表的存储及基本操作(整理)
- 线性表存储和操作
- Python数据结构之——字典
- (数据结构第五章)广义表的头尾链表存储表示
- 【数据结构】用栈检测括号是否匹配
- 【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)
- 【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)
- 【数据结构】用C++实现双循环链表的各种操作(包括头删,尾删,插入,逆序,摧毁,清空等等)
- 【数据结构】用C++实现双链表的各种操作(包括头删,尾删,插入,逆序,摧毁,清空等等)
- 数据结构与算法分析学习笔记(1)--排序
- 几种常见的【排序】与【数据结构】
- 设计包含min函数的栈。
- C++ 数据结构 双链表(模板类)
- 数据结构面试题总结8——数组:数组循环移位
- 数据结构之---C/C++实现稀疏矩阵的十字链表