둥지/알고리즘
리스트 구현
by 까닭
2023. 2. 17.
#include <iostream>
template<typename T>
class LinkedList
{
class Node
{
friend LinkedList;
public:
Node() {};
Node(T& _data)
: data(_data), next(nullptr), prev(nullptr)
{
}
T data;
Node* next;
Node* prev;
};
public:
LinkedList()
: head(new Node())
, tail(new Node())
{
head->next = tail;
tail->prev = head;
}
~LinkedList()
{
Node* node = head;
while (nullptr != node)
{
Node* next = node->next;
delete node;
node = nullptr;
node = next;
}
}
void push_back(T& _data)
{
Node* newNode = new Node(_data);
newNode->prev = tail->prev;
tail->prev->next = newNode;
tail->prev = newNode;
newNode->next = tail;
}
void push_front(T& _data)
{
Node* newNode = new Node(_data);
newNode->next = head->next;
head->next->prev = newNode;
head->next = newNode;
newNode->prev = head;
}
private:
Node* head;
Node* tail;
};
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
LinkedList<int> List{};
int a = 1;
int b = 2;
int c = 3;
List.push_back(a);
List.push_back(b);
List.push_front(c);
}