首页 > 代码库 > 栈、队列的C++实现
栈、队列的C++实现
#include <string.h>#include <stdlib.h>#include <iostream>#include <exception>using namespace std;class MyException : public exception{public: MyException() :exception("the stack is empty...\n") { } MyException(int a) :exception("the queue is empty...\n") { }};template <typename T>class Stack{ int Size; int Room; T* data;public: Stack() { Size = 0; Room = 0; data = http://www.mamicode.com/NULL;"/*test of my stack*/\n\n"; cout << "***********************\n"; Stack<int> s; cout << "the stack has: " << s.size() << " elements...\n"; cout << "the stack can contain: " << s.room() << " elements...\n"; for (int i = 0; i < 100; ++i) s.push(i); cout << "the stack has: " << s.size() << " elements...\n"; cout << "the stack can contain: " << s.room() << " elements...\n"; s.push(30); cout << "the stack has: " << s.size() << " elements...\n"; cout << "the stack can contain: " << s.room() << " elements...\n"; cout << "the top element is " << s.getTop() <<"...\n"; s.pop(); cout << "the top element is " << s.getTop() << "...\n"; cout << "the stack is empty? " << s.isEmpty()<<"...\n"; s.clear(); cout << "the stack is empty? " << s.isEmpty() <<"...\n\n"; cout << "/*test of my queue*/\n\n"; cout << "***********************\n"; Queue<int> t; cout << "the queue has: " << t.size() << " elements...\n"; cout << "the queue can contain: " << t.room() << " elements...\n"; for (int j = 0; j < 100; ++j) t.enqueue(j); cout << "the queue has: " << t.size() << " elements...\n"; cout << "the queue can contain: " << t.room() << " elements...\n"; t.enqueue(-1); cout << "the queue has: " << t.size() << " elements...\n"; cout << "the queue can contain: " << t.room() << " elements...\n"; cout << "the top element is " << t.getHead() <<"...\n"; t.dequeue(); cout << "the queue has: " << t.size() << " elements...\n"; cout << "the queue can contain: " << t.room() << " elements...\n"; cout << "the top element is " << t.getHead() << "...\n"; cout << "the queue is empty? " << t.isEmpty()<<"...\n"; t.clear(); cout << "the queue is empty? " << t.isEmpty() <<"...\n"; return 0;}//栈的结构通过连续内存(数组)来模拟,数组的尾端相当于栈顶//出栈操作并没有将栈顶元素删除,只是通过Size自减1,使得原栈顶元素无法访问//队列的结构同样也是通过连续内存(数组)来模拟,数组的尾端相当于队首//出列操作也同样没有将队首元素删除,只是通过Head自加1,使得原队首元素无法访问
栈、队列的C++实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。