본문 바로가기
C++ Programming

[C++ Programming] Template을 사용한 Doubly Linked List 구현

by TYB 2024. 3. 17.
반응형

 

#include <iostream>

template<typename T>
class Node {
public:
    T data;
    Node<T>* prev;
    Node<T>* next;

    Node(T value) : data(value), prev(nullptr), next(nullptr) {}
};

template<typename T>
class DoublyLinkedList {
private:
    Node<T>* head;
    Node<T>* tail;
public:
    DoublyLinkedList() : head(nullptr), tail(nullptr) {}

    void insertFront(T value) {
        Node<T>* newNode = new Node<T>(value);
        if (!head) {
            head = tail = newNode;
        }
        else {
            newNode->next = head;
            head->prev = newNode;
            head = newNode;
        }
    } 

    void insertBack(T value) {
        Node<T>* newNode = new Node<T>(value);
        if (!tail) {
            head = tail = newNode;
        }
        else {
            tail->next = newNode;
            newNode->prev = tail;
            tail = newNode;
        }
    }

    void display() {
        Node<T>* temp = head;
        while (temp) {
            std::cout << temp->data << " ";
            temp = temp->next;
        }
        std::cout << std::endl;
    }
};

int main() {
    DoublyLinkedList<int> intdll;
    DoublyLinkedList<char> chardll;
    intdll.insertFront(1);
    intdll.insertFront(2);
    intdll.insertBack(3);
    intdll.insertBack(4);
    intdll.display(); // Output: 2 1 3 4
    chardll.insertFront('a');
    chardll.insertFront('b');
    chardll.insertBack('c');
    chardll.insertBack('d');
    chardll.display(); // Output: b a c d

    return 0;
}

 

 

 

 

 

실행 결과를 보면 아래와 같습니다.

 

반응형