[c언어] C 언어에서의 데이터 구조 구현

C 언어는 다양한 데이터 구조를 구현하는 데 사용될 수 있는 강력한 언어입니다. 이 포스트에서는 C 언어를 사용하여 배열, 링크드 리스트, 스택, 큐 및 트리와 같은 데이터 구조를 구현하는 방법에 대해 알아볼 것입니다.

목차

  1. 배열 구현
  2. 링크드 리스트 구현
  3. 스택 구현
  4. 큐 구현
  5. 트리 구현

배열 구현

#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    for(int i = 0; i < 5; i++) {
        printf("%d\n", arr[i]);
    }
    return 0;
}

링크드 리스트 구현

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

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

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

    head = (struct Node*)malloc(sizeof(struct Node));
    second = (struct Node*)malloc(sizeof(struct Node));
    third = (struct Node*)malloc(sizeof(struct Node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    return 0;
}

스택 구현

#include <stdio.h>
#define MAX_SIZE 100

int stack[MAX_SIZE];
int top = -1;

void push(int item) {
    if(top == MAX_SIZE - 1) {
        printf("Stack Overflow\n");
    } else {
        stack[++top] = item;
    }
}

int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        return stack[top--];
    }
}

int main() {
    push(1);
    push(2);
    push(3);
    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", pop());
    return 0;
}

큐 구현

#include <stdio.h>
#define MAX_SIZE 100

int queue[MAX_SIZE];
int front = 0, rear = -1;

void enqueue(int item) {
    if(rear == MAX_SIZE - 1) {
        printf("Queue is full\n");
    } else {
        queue[++rear] = item;
    }
}

int dequeue() {
    if(front > rear) {
        printf("Queue is empty\n");
        return -1;
    } else {
        return queue[front++];
    }
}

int main() {
    enqueue(1);
    enqueue(2);
    enqueue(3);
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    printf("%d\n", dequeue());
    return 0;
}

트리 구현

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

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

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

int main() {
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    return 0;
}

위의 코드 예제는 C 언어를 사용하여 배열, 링크드 리스트, 스택, 큐 및 트리를 구현하는 방법을 보여줍니다. C 언어를 사용하여 다양한 데이터 구조를 구현하고 사용함으로써 프로그래밍 실력을 향상시킬 수 있습니다.

참고 자료