본문 바로가기
C and C++/C and C++ Examples

[C Examples] Struct를 활용하여 특정 위치의 값을 출력하거나 출력하는 순서를 바꿔보기

by Henry Cho 2023. 10. 11.
728x90

Struct를 활용하여 특정 위치의 값을 출력하거나 출력하는 순서를 바꿔보기

포스트 난이도: HOO_Junior


# Example codes

C언어에서 구조체라고 부르는 Struct은 Pointer와 함께 사용되는 편리한 기능 중 하나이다. 아마 C언어를 배우기 전에 다른 프로그래밍 언어를 배워본 적이 없거나 이제 막 전공자로서 공부를 시작했다면, 이 부분을 익히는 게 다소 어렵게 느껴질 수 있다. 하지만 모든 프로그래밍 언어가 그렇듯이 사람을 위한 언어이다 보니, 기계어를 익히는 것보다 훨씬 쉽다고 긍정적으로 생각하면서 차근차근 보면 생각보다 어렵지 않은 개념이다.

 

Struct은 마치 글에서 "서식"과 비슷한 역할을 수행하는데, 반복적으로 사용되는 구조를 특정화하여 매번 선언하고 정의할 필요없이 쉽게 가져다 사용할 수 있다. 이로 인해 실질적인 메인 코드에서는 짧게 작성하여 가독성도 좋아지고 추후에 코드도 쉽게 수정이 가능하다. Struct을 익혀야지만 이후에 포인터에 대해서도 자유롭게 사용이 가능하기에 꼭 익혀야 되는 개념이며, 특히 다른 프로그래밍 언어를 사용하더라도 작성 방법이나 기능에 대한 사용이 다소 다를 뿐 다 똑같기 때문에 꼭 개념을 확실히 익히고 가는 것이 좋다.

 

Struct을 익히는데 있어 가장 좋은 것은 아래의 예제코드처럼 다양한 Struct을 활용한 예제들을 보고 직접 작성해 보면서 익혀나가는 것이다. 아래의 예제코드의 경우 Struct을 활용해서 입력된 값들 중에서 특정 위치에 존재하는 값을 출력하거나 출력되는 순서를 바꾸는 등과 같은 결과를 살펴볼 수 있다. 아래의 예제코드를 참고해서 Struct에 대한 기능을 익혀보도록 하자.


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

// Define structure node with
struct node {
    int value;
    struct node* next;
    struct node* prev;
};

// Set head pointer to NULL
struct node* head = NULL;

// Function to display the list
void displayList() {
    struct node* nodePtr = head;
    struct node* LastNode = NULL;
    int count = 0;

    if (head == NULL) {
        printf("List is empty\n");
        return;
    }

    printf("Values in the list: ");
    while (nodePtr != NULL) {
        printf("%d ", nodePtr->value);
        LastNode = nodePtr;
        nodePtr = nodePtr->next;
        count++;
    }

    printf("\nPrinting backwards: ");
    while (LastNode != NULL) {
        printf("%d ", LastNode->value);
        LastNode = LastNode->prev;
    }

    nodePtr = head;
    for (int i = 0; i < count / 2; i++) {
        nodePtr = nodePtr->next;
    }

    printf("\n\nMiddle value: %d\n", nodePtr->value);

    if (nodePtr->next != NULL) {
        printf("Value to the right: %d\n", nodePtr->prev->value);
    } else {
        printf("No value to the right\n");
        
    }
       if (nodePtr->prev != NULL) {
        printf("Value to the left: %d\n", nodePtr->next->value);
    } else {
        printf("No value to the left\n");
    }
}

// Function to insert an element at the end of the list
void insert_end(int num) {
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    struct node* nodePtr = head;

    newnode->value = num;
    newnode->next = NULL;

    if (head == NULL) {
        head = newnode;
        newnode->prev = NULL;
    } else {
        while (nodePtr->next != NULL) {
            nodePtr = nodePtr->next;
        }
        nodePtr->next = newnode;
        newnode->prev = nodePtr;
    }
}

int main() {
    // Call insert_end
    insert_end(123);
    insert_end(699);
    insert_end(873);
    insert_end(597);
    insert_end(596);
    insert_end(324);
    insert_end(156);

    // Call displayList()
    displayList();

    printf("\n");

    return 0;
}

Figure1. 예제코드 결과


# github link

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/struct_list


 

 
728x90

댓글