实现了链表
BUT运行时崩溃
调试了一下,是地址非法访问......
看起来没什么问题啊(逃
#include <bits/stdc++.h>
#include <initializer_list>
namespace myList {
void __handler() {
std::cerr << "List error: no more memory";
exit(0);
}
template<class ElementType>
class list {
protected:
struct listNode {
listNode *prev;
listNode *next;
ElementType data;
} head;
size_t __size;
public:
typedef ElementType value_type;
protected:
typedef listNode* linkType;
typedef ElementType& reference;
typedef const ElementType& const_reference;
public:
struct iterator {
linkType cursor;
inline reference operator*()
{ return cursor->data; }
inline bool operator!=(iterator iteratorCompareWith)
{ return cursor != iteratorCompareWith.cursor; }
inline void operator=(linkType nodePointer)
{ cursor = nodePointer; }
inline iterator operator++() {
cursor = cursor->next;
return *this;
}
};
inline iterator change_to_iterator(linkType linkType_for_changing) {
iterator tmp;
tmp.cursor = linkType_for_changing;
return tmp;
}
inline iterator begin()
{ return change_to_iterator(head.next); }
inline iterator end()
{ return change_to_iterator(&head); }
protected:
inline void connect(listNode &left, listNode &right) {
left.next = &right;
right.prev = &left;
}
inline void connect(linkType left, linkType right)
{ connect(*left, *right); }
public:
template<class FunctionType>
inline void set_list_new_handler(FunctionType handler)
{ std::set_new_handler(handler); }
public:
list(std::initializer_list<ElementType> elements)
{ list((ElementType*)elements.begin(), (ElementType*)elements.end()); }
list(ElementType* first, ElementType* last) {
set_list_new_handler(myList::__handler);
if(first == last) return ;
linkType prev_listNode_address = &head;
linkType next_listNode_address;
for(; first != last; ++first) {
next_listNode_address = create_node(*first);
connect(prev_listNode_address, next_listNode_address);
prev_listNode_address = next_listNode_address;
}
connect(next_listNode_address, &head);
}
protected:
inline linkType create_node()
{ return new listNode; }
inline linkType create_node(const_reference val) {
linkType new_node_address = create_node();
new_node_address->data = val;
return new_node_address;
}
} ;
}
int main()
{
myList::list<int> myList = {1, 2, 3};
for(myList::list<int>::iterator i = myList.begin(); i != myList.end(); ++i)
std::cout << *i << " ";
return 0;
}
谢谢你的代码,让我学到了很多知识
我推测你是在 函数list(std::initializer_list<ElementType> elements) ;
中调用了另一个构造函数list(ElementType* first, ElementType* last)
造成的问题;你可以单步调试试试看,初始化后的mylist 没有任何变化;
原因: 执行一次构造函数就会生成一个 对象的示例,但是如果在构造函数中嵌套调用构造函数那么他仅仅只是在你构造函数的 [栈] 上实例化了一个对象,但是并没有将内容复制到你想要复制到的外层构造函数的那个对象里面去;
你可以试着改成 (*this) = list(ElementType* first, ElementType* last)
,
不过如果你这样的话需要重写操作符 '=' 函数;
如果你不想重写操作符,
那么你可以把你在list(ElementType* first, ElementType* last)
里的内容复制到 list(std::initializer_list<ElementType> elements) ;
即可;
不知道这样你可不可以理解,需要的话可以再次评论大家讨论,
最后再次谢谢你的代码也让我学到了东西~~~