C_C++

(C언어) 원형 연결리스트 circular linked list

고니자니 2023. 10. 13. 08:30
반응형

새 노드를 뒤쪽에 삽입하는 원형 연결리스트의 C언어 코드입니다.

 

#include <stdio.h>
#include <stdlib.h>

// 원형 연결 리스트의 노드를 나타내는 구조체
struct Node {
    int data;
    struct Node* next;
};

// 새 노드 생성 함수
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 뒤쪽에 노드 추가 함수
struct Node* insertAtEnd(struct Node* head, int data) {
    struct Node* newNode = createNode(data);

    if (head == NULL) {
        newNode->next = newNode; // 처음 노드가 생성될 때, 자기 자신을 가리킴
        return newNode;
    }

    newNode->next = head->next; // 새 노드가 첫 노드를 가리키게 함
    head->next = newNode; // 현재 끝 노드가 새 노드를 가리키게 함
    return newNode;
}

// 원형 연결 리스트 출력 함수
void display(struct Node* head) {
    if (head == NULL) {
        printf("리스트가 비어있습니다.\n");
        return;
    }

    struct Node* current = head;
    do {
        printf("%d -> ", current->data);
        current = current->next; 
    } while (current != head);
    printf(" (head)\n");
}

int main() {
    struct Node* head = NULL;

    // 뒤쪽에 몇 개의 노드 추가
    head = insertAtEnd(head, 100);
    head = insertAtEnd(head, 200);
    head = insertAtEnd(head, 300);
    head = insertAtEnd(head, 400);
    head = insertAtEnd(head, 500);

    // 원형 연결 리스트 출력
    printf("원형 연결 리스트: ");
    display(head);

    return 0;
}

 

 

 

728x90
반응형