queue不能遍历,就想着自己写个能遍历的队列,寻思着就写了个循环链表,完全跑题了,但是也发现了一些问题
一个结构体:
struct A
{
int x;
A(int x):x(x){}
};
循环链表:
struct danmuLb{
A *x;
static danmuLb *head;
static danmuLb *tail;
danmuLb *next;
danmuLb *previous;
danmuLb(A &X):
x(&X)
{
previous = (danmuLb::tail == nullptr)?this: danmuLb::tail;
next = previous->next;
previous->next = this;
next->previous = this;
if(danmuLb::tail == nullptr) danmuLb::head = this;
danmuLb::tail = this;
}
~danmuLb(){
danmuLb::tail = (next == this)?nullptr: previous;
if(danmuLb::tail == nullptr) danmuLb::head = nullptr;
previous->next = next;
next->previous = previous;
delete x;
}
void print() {cout<<"num of this is "<<x->x<<endl;}
// queue这种链表没做迭代器的原因找到了!
// 没法让指针重载自增++
static void destroy() {
danmuLb *now = danmuLb::head;
danmuLb *tmp;
while(now->next != now){
tmp = now->next;
delete now;
now = tmp;
}
delete now;
}
};
danmuLb *danmuLb::head = nullptr;
danmuLb *danmuLb::tail = nullptr;
main函数:
int main(){
// 记下来研究一下
// new danmuLb(A(2));
new danmuLb(*(new A(2)));
new danmuLb(*(new A(3)));
cout<<typeid(A(8)).name()<<endl;
cout<<typeid(*(new A(4))).name()<<endl;
// new danmuLb(new A(3));
//...
danmuLb *tmp = tmp->head;
tmp->print();
tmp = tmp->next;
tmp->print();
tmp = tmp->next;
tmp->print();
tmp = tmp->next;
tmp->print();
tmp = tmp->next;
tmp->print();
tmp->destroy();
cout<<tmp->head<<' '<<tmp->tail;
return 0;
}
问题:
- 自定义类型的指针的运算符能不能遍历?
- 关于不能new danmuLb(A(2)), 为什么不返回临时数据A(2)的引用,对声明的具体过程还不够熟悉