Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어 동적 연결 리스트로 자동차 정보 저장하기 – 완전 정리

연결 리스트(Linked List)는 동적 메모리 할당을 사용하는 자료구조입니다. 즉, 데이터의 개수에 따라 크기가 유연하게 늘어나거나 줄어들 수 있으며, 여러 개의 노드(Node)가 모여 하나의 리스트를 이룹니다.

노드의 구성 요소

노드는 다음 두 가지 부분으로 구성됩니다.

  • 데이터(Data) – 실제 저장하고자 하는 값
  • 링크(Link) – 다음 노드를 가리키는 포인터

연결 리스트의 종류

C 프로그래밍에서 사용되는 연결 리스트는 크게 다음과 같이 나눌 수 있습니다.

  • 단일 연결 리스트(Singly Linked List)
  • 이중 연결 리스트(Doubly Linked List)
  • 원형 단일 연결 리스트(Circular Singly Linked List)
  • 원형 이중 연결 리스트(Circular Doubly Linked List)

알고리즘

아래 알고리즘은 동적 연결 리스트를 활용해 자동차 정보를 저장하는 절차입니다.

  1. 1단계 – 구조체 변수를 선언합니다.
  2. 2단계 – 출력(display) 함수를 정의합니다.
  3. 3단계 – 변수에 동적 메모리 할당(malloc)을 수행합니다.
  4. 4단계 – do-while 반복문을 사용해 차량 정보를 입력받습니다.
  5. 5단계 – 출력 함수를 호출한 뒤 2단계로 돌아갑니다.

예제 코드

다음은 동적 연결 리스트를 이용해 자동차 정보를 저장하는 C 프로그램입니다. 각 차량의 모델명, 색상, 연식을 입력받으며, 그중 2010년 이후 생산되면서 노란색인 차량만 화면에 출력합니다.

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

struct node {
    char model[10], color[10];
    int year;
    struct node *next;
};

struct node *temp, *head;

void display(struct node *head) {
    temp = head;
    while (temp != NULL) {
        if (temp->year > 2010 && (strcmp("yellow", temp->color) == 0))
            printf(" %s \t\t %s \t\t %d", temp->model, temp->color, temp->year);
        temp = temp->next;
        printf("\n");
    }
}

int main() {
    int n;
    char option, enter;
    head = (struct node *)malloc(sizeof(struct node));
    temp = head;
    do {
        printf("\nenter car model: ");
        scanf("%s", temp->model);
        printf("enter car color: ");
        scanf("%s", temp->color);
        printf("enter car year: ");
        scanf("%d", &temp->year);
        printf("\nDo you want continue Y(es) | N(o) : ");
        scanf("%c", &enter);
        scanf("%c", &option);
        if (option != 'N') {
            temp->next = (struct node *)malloc(sizeof(struct node));
            temp = temp->next;
        } else {
            temp->next = NULL;
        }
    } while (option != 'N');
    display(head);
    return 0;
}

코드 설명

  • struct node 구조체는 모델명(model), 색상(color), 연식(year), 그리고 다음 노드를 가리키는 포인터(next)로 구성되어 있습니다.
  • malloc() 함수로 노드마다 메모리를 동적으로 할당하여, 입력되는 차량 수에 따라 리스트가 자유롭게 확장됩니다.
  • do-while 문 안에서 사용자가 'N'을 입력할 때까지 새로운 노드를 계속 추가하며, 종료 시 마지막 노드의 next를 NULL로 설정해 리스트의 끝을 표시합니다.

실행 결과

위 프로그램을 실행하면 다음과 같이 차량 정보를 순서대로 입력받습니다.

enter car model: I20
enter car color: white
enter car year: 2016
Do you want continue Y(es) | N(o) : Y
enter car model: verna
enter car color: red
enter car year: 2018
Do you want continue Y(es) | N(o) : Y
enter car model: creta
enter car color: Maroon
enter car year: 2010
Do you want continue Y(es) | N(o) : N

입력이 끝나면 display 함수가 호출되어 조건(2010년 초과 생산 + 노란색)에 맞는 차량만 필터링되어 출력됩니다.