자료구조는 데이터를 저장하고 조작하기 위한 구조체 또는 메커니즘으로, 프로그램에서 데이터의 효율적인 조작을 가능하게 합니다. 각 자료구조는 특정한 연산을 수행하는 데 효과적이며, C 언어를 사용하여 몇 가지 자료구조를 설명해보겠습니다.
배열은 동일한 자료형의 원소들을 순차적으로 저장하는 선형 자료구조입니다.
#include <stdio.h>
int main() {
// 정수형 배열 선언 및 초기화
int arr[5] = {1, 2, 3, 4, 5};
// 배열 순회 및 출력
for (int i = 0; i < 5; ++i) {
printf("%d ", arr[i]);
}
return 0;
}
연결 리스트는 각 노드가 데이터와 다음 노드를 가리키는 포인터로 이루어진 구조체로 구성된 자료구조입니다.
#include <stdio.h>
#include <stdlib.h>
// 연결 리스트 노드 정의
struct Node {
int data;
struct Node* next;
};
int main() {
// 연결 리스트 초기화
struct Node* head = NULL;
// 노드 추가
head = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = NULL;
// 노드 순회 및 출력
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
스택은 후입선출(LIFO) 구조로, 데이터를 맨 위에 추가하고 맨 위에서만 제거할 수 있는 자료구조입니다.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
struct Stack {
int arr[MAX_SIZE];
int top;
};
// 스택 초기화
void initStack(struct Stack* stack) {
stack->top = -1;
}
// 스택에 요소 추가
void push(struct Stack* stack, int item) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack->arr[++stack->top] = item;
}
// 스택에서 요소 제거
int pop(struct Stack* stack) {
if (stack->top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack->arr[stack->top--];
}
int main() {
struct Stack myStack;
initStack(&myStack);
// 스택에 요소 추가
push(&myStack, 1);
push(&myStack, 2);
push(&myStack, 3);
// 스택에서 요소 제거 및 출력
printf("%d ", pop(&myStack));
printf("%d ", pop(&myStack));
printf("%d ", pop(&myStack));
return 0;
}
큐는 선입선출(FIFO) 구조로, 데이터를 뒤에서 추가하고 앞에서만 제거할 수 있는 자료구조입니다.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
struct Queue {
int arr[MAX_SIZE];
int front, rear;
};
// 큐 초기화
void initQueue(struct Queue* queue) {
queue->front = queue->rear = -1;
}
// 큐에 요소 추가
void enqueue(struct Queue* queue, int item) {
if ((queue->rear + 1) % MAX_SIZE == queue->front) {
printf("Queue Overflow\n");
return;
}
if (queue->front == -1) {
queue->front = queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
queue->arr[queue->rear] = item;
}
// 큐에서 요소 제거
int dequeue(struct Queue* queue) {
if (queue->front == -1) {
printf("Queue Underflow\n");
return -1;
}
int item = queue->arr[queue->front];
if (queue->front == queue->rear) {
queue->front = queue->rear = -1;
} else {
queue->front = (queue->front + 1) % MAX_SIZE;
}
return item;
}
int main() {
struct Queue myQueue;
initQueue(&myQueue);
// 큐에 요소 추가
enqueue(&myQueue, 1);
enqueue(&myQueue, 2);
enqueue(&myQueue, 3);
// 큐에서 요소 제거 및 출력
printf("%d ", dequeue(&myQueue));
printf("%d ", dequeue(&myQueue));
printf("%d ", dequeue(&myQueue));
return 0;
}