본문 바로가기
둥지/알고리즘

리스트 구현

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);
}

'둥지 > 알고리즘' 카테고리의 다른 글

Array, Vector 구현  (0) 2023.02.20
[백준 1992] 쿼드 트리  (0) 2023.02.20
큐 구현  (0) 2023.02.10
스택 구현  (0) 2023.02.09
가변 배열 구현  (0) 2023.02.09