昨天可能是太晚了,晕了
改进了一下:
struct A
{
int x;
A(int x):x(x){}
void setX(int x){this->x = x;}
int getX(){return x;}
void print(){
if(this == nullptr){
// cout<<"print error: this is NULL"<<endl;
cout<<"this is NULL"<<endl;
return;
}
// cout<<this<<endl;
cout<<"value is: "<<x<<endl<<endl;
}
};
//不算容器
//目前这样用着更爽
template <typename T> class MyQueue
{
public:
struct item{
T *x;
item *next;
item(T *X):
x(X),
next(nullptr)
{
}
~item() {
delete x;
}
};
private:
item *head;
item *tail;
item *now;
public:
MyQueue():
head(nullptr),
tail(nullptr),
now(nullptr)
{};
~MyQueue(){
clear();
};
void push(T *X) {
if(tail != nullptr) tail->next = new item(X), tail = tail->next;
else tail = head = now = new item(X);
};
void pop() {
if(head == nullptr){
// cout<<"pop error: it's empty now"<<endl;
tail = now = nullptr;
return;
}
item *tmp = head;
if(now == head) now = head->next;
head = head->next;
//???
delete tmp;
};
T* front() {
if(head == nullptr){
// cout<<"front error: it's empty now"<<endl;
return nullptr;
}
return head->x;
}
T* back() {
if(tail == nullptr){
// cout<<"back error: it's empty now"<<endl;
return nullptr;
}
return tail->x;
}
T* nextone(){
if(now == nullptr){
// cout<<"nextone error: over"<<endl;
return nullptr;
}
item *tmp = now;
now = now->next;
return tmp->x;
}
bool isSafe(){
return !(now == nullptr);
}
void reset(){
now = head;
}
void clear(){
while(head != nullptr){
item *tmp = head;
head = head->next;
tmp->~item();
}
head = tail = nullptr;
};
};
int main(){
MyQueue<A> tmp;
for(int i = 1; i <= 3; i++) tmp.push(new A(i));
tmp.front()->print();
tmp.back()->print();
tmp.pop();
tmp.front()->print();
A *tmpA = new A(0);
tmpA = tmp.nextone();
cnm(1);
tmpA->print();
tmpA = tmp.nextone();
cnm(2);
tmpA->print();
tmpA = tmp.nextone();
cnm(3);
tmpA->print();
tmpA = tmp.nextone();
cnm(4);
tmpA->print();
cnm(5);
tmp.pop();
tmp.pop();
tmp.pop();
// cout<<"front: "<<tmp.front()<<" back: "<<tmp.back()<<endl;
tmp.front()->print();
tmp.back()->print();
// for(int i = 1; i <= 10; i++)
// tmp.push(new A(i));
// while(tmp.isSafe())
// tmp.nextone()->print();
// tmp.reset();
// while(tmp.isSafe())
// tmp.nextone()->print();
return 0;
}
输出结果: