내내 개발만하다가 요즘들어 알고리즘 공부를 함으로써 자료구조를 다시 한번 정리하려한다. 알고리즘 문제를 해결할때 도움이 되고자 간단하고 빠르게 자료구조에 대해 코드 위주로 정리해보았다 !!
// 배열 선언 및 초기화
int[] arr = {1, 2, 3, 4, 5};
// 배열 요소 접근 및 출력
System.out.println(arr[2]); // 출력: 3
// 배열 요소 삽입 (새로운 배열 필요)
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, 2);
newArr[2] = 6; // 6을 삽입
System.arraycopy(arr, 2, newArr, 3, arr.length - 2);
arr = newArr;
System.out.println(java.util.Arrays.toString(arr)); // 출력: [1, 2, 6, 3, 4, 5]
// 배열 요소 삭제 (새로운 배열 필요)
int[] newArr2 = new int[arr.length - 1];
System.arraycopy(arr, 0, newArr2, 0, 2);
System.arraycopy(arr, 3, newArr2, 2, arr.length - 3);
arr = newArr2;
System.out.println(java.util.Arrays.toString(arr)); // 출력: [1, 2, 3, 4, 5]
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
// 노드 추가
void append(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
// 리스트 출력
void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
// 사용 예시
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.printList(); // 출력: 1 2 3
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
// 데이터 삽입
stack.push(1);
stack.push(2);
stack.push(3);
// 데이터 제거 및 출력
System.out.println(stack.pop()); // 출력: 3
// 데이터 접근만 (제거하지 않음)
System.out.println(stack.peek()); // 출력: 2
// 스택이 비어있는지 확인
System.out.println(stack.isEmpty()); // 출력: false
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> queue = new LinkedList<>();
// 데이터 삽입
queue.add(1);
queue.add(2);
queue.add(3);
// 데이터 제거 및 출력
System.out.println(queue.poll()); // 출력: 1
// 데이터 접근만 (제거하지 않음)
System.out.println(queue.peek()); // 출력: 2
// 큐가 비어있는지 확인
System.out.println(queue.isEmpty()); // 출력: false
import java.util.HashMap;
HashMap<String, Integer> hashMap = new HashMap<>();
// 데이터 삽입
hashMap.put("apple", 1);
hashMap.put("banana", 2);
hashMap.put("cherry", 3);
// 데이터 접근
System.out.println(hashMap.get("banana")); // 출력: 2
// 데이터 삭제
hashMap.remove("apple");
System.out.println(hashMap.containsKey("apple")); // 출력: false
class TreeNode {
int data;
TreeNode left, right;
TreeNode(int data) {
this.data = data;
left = right = null;
}
}
class BinaryTree {
TreeNode root;
// 노드 삽입
TreeNode insert(TreeNode node, int data) {
if (node == null) {
return new TreeNode(data);
}
if (data < node.data) {
node.left = insert(node.left, data);
} else if (data > node.data) {
node.right = insert(node.right, data);
}
return node;
}
// 중위 순회 (In-order Traversal)
void inOrder(TreeNode node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
}
}
// 사용 예시
BinaryTree tree = new BinaryTree();
tree.root = tree.insert(tree.root, 5);
tree.insert(tree.root, 3);
tree.insert(tree.root, 7);
tree.inOrder(tree.root); // 출력: 3 5 7
import java.util.LinkedList;
class Graph {
private int numVertices;
private LinkedList<Integer>[] adjList;
Graph(int numVertices) {
this.numVertices = numVertices;
adjList = new LinkedList[numVertices];
for (int i = 0; i < numVertices; i++) {
adjList[i] = new LinkedList<>();
}
}
// 간선 추가
void addEdge(int src, int dest) {
adjList[src].add(dest);
}
// 그래프 출력
void printGraph() {
for (int i = 0; i < numVertices; i++) {
System.out.print("Vertex " + i + ":");
for (Integer node : adjList[i]) {
System.out.print(" -> " + node);
}
System.out.println();
}
}
}
// 사용 예시
Graph graph = new Graph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.printGraph();
// 출력:
// Vertex 0: -> 1 -> 4
// Vertex 1: -> 2 -> 3
// Vertex 2:
// Vertex 3:
// Vertex 4:
import java.util.PriorityQueue;
PriorityQueue<Integer> pq = new PriorityQueue<>();
// 데이터 삽입
pq.add(3);
pq.add(1);
pq.add(5);
// 데이터 접근 및 제거 (기본적으로 오름차순)
System.out.println(pq.poll()); // 출력: 1
System.out.println(pq.poll()); // 출력: 3
System.out.println(pq.poll()); // 출력: 5
// 우선순위가 높은 값 (내림차순 정렬)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(java.util.Collections.reverseOrder());
maxHeap.add(3);
maxHeap.add(1);
maxHeap.add(5);
System.out.println(maxHeap.poll()); // 출력: 5
System.out.println(maxHeap.poll()); // 출력: 3
System.out.println(maxHeap.poll()); // 출력: 1