반응형
    
    
    
  
#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;
}
실행 결과를 보면 아래와 같습니다.

반응형
    
    
    
  'C++ Programming' 카테고리의 다른 글
| [C++ Programming] 문자열 변환 c_str() 함수 (0) | 2024.07.06 | 
|---|---|
| [C++] Vector 공부 (0) | 2024.07.06 | 
| [C++] MFC에서 CString 사용 시 printf 값이 이상할 경우 해결 방법 (0) | 2023.10.31 | 
| [C++] visual studio와 maria db 연동 후 값 읽어오기 (0) | 2023.10.25 | 
| 프로그램 실행 시 메모리 구조 (0) | 2023.10.25 |