stl의 list 만들어 보기
Programing/자료구조 2012. 5. 30. 15:29 |template <class T>
class List
{
class Node
{
public:
Node* after;
Node* before;
T _data;
Node( T data = 0 )
{
after = NULL;
before = NULL;
_data = data;
}
};
Node* top;
Node* bottum;
int size;
public:
class Iter
{
Node* _pos;
friend class List;
public:
Iter( Node* pNode = NULL )
{
_pos = pNode;
}
Iter(const Iter &it)
{
_pos = it._pos;
}
void operator=( Iter it )
{
_pos = it._pos;
}
T operator*()
{
return _pos->_data;
}
T* operator->()
{
return &_pos->_data;
}
const bool operator==(Iter pIter)
{
return _pos == pIter._pos;
}
const bool operator!=(Iter pIter)
{
return _pos != pIter._pos;
}
void operator++(int)
{
if (_pos != NULL)
{
_pos = _pos->after;
}
}
void operator++()
{
if (_pos != NULL)
{
_pos = _pos->after;
}
}
};
List()
{
top = new Node();
bottum = new Node();
size = 0;
top->after = bottum;
bottum->before = top;
}
~List()
{
clean();
delete top;
delete bottum;
}
void clean()
{
Iter iter( begin() );
for ( iter; iter != end(); )
{
iter = eraser(iter);
}
}
Iter eraser( Iter pIter )
{
if (size > 0)
{
Node* pPos = pIter._pos;
if ( pPos->before )
pPos->before->after = pPos->after;
if ( pPos->after )
pPos->after->before = pPos->before;
Node* pCurrnet = pPos->after;
delete pPos;
pIter = pCurrnet;
size--;
}
return pIter;
}
Iter end()
{
return Iter(bottum);
}
Iter begin()
{
return Iter(top->after);
}
void push_back( T pData )
{
insert( end(), pData );
}
void insert( Iter pIter, T pData )
{
Node* pNewNode = new Node( pData );
pNewNode->before = pIter._pos->before;
pIter._pos->before->after = pNewNode;
pIter._pos->before = pNewNode;
pNewNode->after = pIter._pos;
size++;
}
};
class jaeho
{
public:
jaeho(int _k =0, float _j = 0.f)
{
k= _k;
j = _j;
}
int k;
float j;
};
void main()
{
List<int> test;
test.push_back(10);
test.push_back(40);
test.push_back(20);
test.push_back(240);
List<int>::Iter iter = test.begin();
iter++;
test.insert(iter,333);
for (List<int>::Iter iter = test.begin(); iter != test.end(); iter++ )
{
printf("%d\n", *iter );
}
printf("\n");
iter = test.begin();
test.eraser(iter);
for (List<int>::Iter iter = test.begin(); iter != test.end(); ++iter )
{
printf("%d\n", *iter );
}
List<jaeho> test2;
test2.push_back(jaeho(20,41.4f));
test2.push_back(jaeho(220,211.6f));
test2.push_back(jaeho(120,52.4f));
for (List<jaeho>::Iter iter = test2.begin(); iter != test2.end(); iter++ )
{
printf("%d %f\n", iter->k , iter->j );
}
}
자료구조 다시 환기할 겸 만들어 봤음
stl에 list의 기능은 다 구현 안했음
기본적인것만 구현
시간 날 때 마다 하나 씩 구현 해봐야 겠다.
'Programing > 자료구조' 카테고리의 다른 글
STL Vector와 List 차이점 (0) | 2012.05.21 |
---|---|
Big - O 표기법 (0) | 2012.05.18 |