实现了链表
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;