队列:
#include <iostream> #include <cstring> #define Max 10 using namespace std; template <typename T> class Queues { public: T data[Max]; int head; int end; Queues():head(0),end(0){memset(data,0,sizeof(data));} Queues(T d) { memset(data,0,sizeof(data)); head=end=0; data[end]=d; end=(end+1)%Max; } //如果队列空则返回真 bool empty() { return head==end; } //back() 返回最后一个元素 T& back() { if(empty()) { cout<<"队列为空"<<endl; } else { return data[end-1]; } } //front() 返回第一个元素 T& front() { if(empty()) { cout<<"队列为空"<<endl; } else { return data[head]; } } //pop() 删除第一个元素 void pop() { if(empty()) { cout<<"队列为空"<<endl; } else { head=(head+1)%Max; } } //push(T d) 在末尾加入一个元素 void push(T d) { if((end+1)%Max==head) { cout<<"队列已满"<<endl; } else { data[end]=d; end=(end+1)%Max; } } //size() 返回队列中元素的个数 int size() { return (end-head+Max)%Max; } void show() { if(empty()) { cout<<"队列为空"<<endl; } else { for(int i=head;i<end;i=(i+1)%Max) { cout<<data[i]<<" "; } } } }; int main() { Queues <int> q1(3); q1.push(2); q1.show(); cout<<"返回最后一个元素"<<q1.front()<<endl; cout<<"返回第一个元素"<<q1.back()<<endl; cout<<"队列中的数目为"<<q1.size()<<endl; q1.pop(); q1.pop(); if(q1.empty()) { cout<<"队列为空"<<endl; } else { cout<<"队列不为空"<<endl; } return 0; }
栈:
#include <iostream> #define Max 10 using namespace std; template <typename T> class Stacks { public: T data[Max]; int data_top; Stacks():data_top(-1){memset(data,0,sizeof(data));} Stacks(T d) { memset(data,0,sizeof(data)); data[0]=d; data_top=0; } // 操作 比较和分配堆栈 //堆栈为空则返回真 bool empty() { return this->data_top==-1? 1:0; } // pop() 移除栈顶元素 void pop() { if(empty()==0) { this->data_top--; } } // push() 在栈顶增加元素 int push(T d) { if(data_top==Max) { cout<<"栈已满"<<endl; return -1; } else { data[data_top+1]=d; data_top++; } } // size() 返回栈中元素数目 int size() { return data_top+1; } // top& () 返回栈顶元素 T top() { return data[data_top]; } void show() { for(int i=data_top;i>=0;i--) { cout<<data[i]<<" "; } } }; int main() { Stacks <int> s1(3); s1.push(2); s1.show(); cout<<"栈中的数目为"<<s1.size()<<endl; cout<<"栈顶的元素为"<<s1.top()<<endl; s1.pop(); s1.pop(); if(s1.empty()) { cout<<"栈为空"<<endl; } else { cout<<"栈不为空"<<endl; } return 0; }