데이터 구조(Data Structure)는 데이터를 효율적으로 저장하고 관리하기 위한 방법을 의미합니다. 데이터 구조는 컴퓨터 과학에서 매우 중요한 개념으로, 다양한 알고리즘의 성능을 좌우합니다. 데이터를 조직화하는 방법에 따라 다양한 데이터 구조가 있으며, 각각의 데이터 구조는 특정 상황에서 더 적합하게 사용될 수 있습니다.
배열 (Array)
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[2]); // 출력: 3
연결 리스트 (Linked List)
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
let list = new LinkedList();
list.append(1);
list.append(2);
스택 (Stack)
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) return "Underflow";
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
}
let stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 출력: 2
큐 (Queue)
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
if (this.items.length === 0) return "Underflow";
return this.items.shift();
}
front() {
return this.items[0];
}
}
let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 출력: 1
트리 (Tree)
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
그래프 (Graph)
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(vertex1, vertex2) {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
let graph = new Graph();
graph.addVertex('A');
graph.addVertex('B');
graph.addEdge('A', 'B');
각 데이터 구조는 특정 상황에 따라 장단점이 있으며, 효율적인 알고리즘 구현을 위해 적절한 데이터 구조를 선택하는 것이 중요합니다. 데이터 구조를 잘 이해하면 더 효율적이고 확장 가능한 프로그램을 작성할 수 있습니다.