2019.09.01 직접구현 (오류가 있을 수 있음)
template<typename T> struct CNode
{
CNode(T _value)
{
value = _value;
}
CNode* next;
CNode* prev;
T value;
};
template<typename T> class CLinkedList
{
private:
CNode<T>* head;
CNode<T>* tail;
int count;
public:
CLinkedList() : head(NULL), tail(NULL), count(0)
{
}
~CLinkedList()
{
clear();
}
public:
int add(T item)
{
CNode<T> *newNode = new CNode<T>(item);
if (count == 0)
{
head = newNode;
tail = newNode;
newNode->next = NULL;
newNode->prev = NULL;
}
else
{
newNode->next = NULL;
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
++count;
return count;
}
int erase(T item)
{
CNode<T> *pThis = head;
while (pThis)
{
if (pThis->value == item)
{
if (pThis->prev)
{
pThis->prev->next = pThis->next;
}
else // prev 가 없다는건 head 를 삭제하는것이므로 다음것을 head 로 임명
{
head = pThis->next;
}
if (pThis->next)
{
pThis->next->prev = pThis->prev;
}
else // next 가 없다는건 tail 을 삭제하는것이므로 이전것을 tail 로 임명
{
tail = pThis->prev;
}
delete pThis;
--count;
break;
}
pThis = pThis->next;
}
return count;
}
void clear()
{
CNode<T> *pThis = head;
while (pThis)
{
CNode<T> *pDelete = pThis;
if (pThis->prev)
pThis->prev->next = pThis->next;
if (pThis->next)
pThis->next->prev = pThis->prev;
pThis = pThis->next;
delete pDelete;
--count;
}
head = NULL;
tail = NULL;
}
int getSize()
{
return count;
}
void printAll()
{
if (count > 0)
{
CNode<T> *pThis = head;
while (pThis)
{
cout << pThis->value << endl;
pThis = pThis->next;
}
}
}
CNode<T>* getHead() { return head; }
CNode<T>* getTail() { return tail; }
};
아래는 사용예
int main(int argc, char* argv[])
{
CLinkedList<int> list;
list.add(10);
list.add(20);
list.add(30);
list.erase(10);
list.printAll();
list.clear();
list.printAll();
_CrtDumpMemoryLeaks();
return 0;
}