CS/C++

C++로 연결 리스트 구현하기

munsik22 2025. 4. 8. 13:21
#include <iostream>

using namespace std;

typedef struct Node {
    int data;
    struct Node* next;
} Node;

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

void appendNode(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

void printList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        cout << current->data << " -> ";
        current = current->next;
    }
    cout << "NULL" << endl;
}

void freeList(Node* head) {
    Node* tmp;
    while (head != NULL) {
        tmp = head;
        head = head->next;
        free(tmp);
    }
}

int main() {
    Node* head = NULL;

    appendNode(&head, 10);
    appendNode(&head, 20);
    appendNode(&head, 30);
    cout << "Linked List: " << endl;
    printList(head);

    freeList(head);
    return 0;
}

코드 실행 결과

'CS > C++' 카테고리의 다른 글

C++로 이진 탐색 트리 구현하기  (0) 2025.04.15
C++로 TIC TAC TOE 게임 구현하기  (0) 2025.04.15
C++로 스택/큐 구현하기  (0) 2025.04.12
C++ 기초 정리  (0) 2025.03.30