배열은 고정 크기의 메모리 공간에 연속적으로 저장된 데이터를 관리하는 자료구조입니다.
각 데이터는 인덱스를 통해 빠르게 접근할 수 있습니다.
| 장점 | 단점 |
|---|---|
| 데이터 접근 속도가 빠름 | 크기 변경이 어려움 (고정 크기) |
| 간단한 구조로 메모리 사용 효율적 | 삽입 및 삭제가 비효율적 (O(n)) |
public class ArrayExample {
public static void main(String[] args) {
int[] array = {10, 20, 30, 40};
// Access
System.out.println("Element at index 2: " + array[2]); // 30
// Update
array[2] = 50;
// Loop through array
for (int num : array) {
System.out.print(num + " ");
}
// Output: 10 20 50 40
}
}
링크드 리스트는 노드(Node)라는 객체가 포인터를 통해 서로 연결된 구조의 자료구조입니다.
각 노드는 데이터와 다음 노드의 주소(참조)를 포함합니다.
| 장점 | 단점 |
|---|---|
| 삽입/삭제가 용이 (O(1), 처음/끝) | 데이터 접근이 느림 (O(n)) |
| 크기가 동적으로 변할 수 있음 | 추가적인 메모리 사용(포인터 저장 공간) |
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedListExample {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
// Traverse and print linked list
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
// Output: 10 20 30
}
}
| 특징 | 배열(Array) | 링크드 리스트(Linked List) |
|---|---|---|
| 메모리 할당 | 연속적인 메모리 공간 | 비연속적인 메모리 공간 |
| 크기 | 고정 크기 | 동적 크기 |
| 데이터 접근 | 빠름 (O(1)) | 느림 (O(n)) |
| 삽입/삭제 | 비효율적 (O(n)) | 효율적 (O(1), 처음/끝에 한정) |
| 구현 복잡도 | 간단 | 복잡 (포인터 관리 필요) |
배열은 빠른 데이터 접근이 필요한 상황에서,링크드 리스트는 삽입/삭제가 빈번한 상황에서 적합하다는 것을 알게 되었습니다.
상황에 맞는 자료구조를 선택하는 것이 효율적인 프로그램을 만드는 데 중요하다는 점을 느꼈습니다.