Dev_TIMI

코틀린(Kotlin)으로 배우는 기본 자료구조 정리: 스택, 큐, 리스트, 해시맵

by its_TIMI

아래는 스택(Stack), 큐(Queue), 리스트(List), 해시맵(HashMap)의 기본 개념과 Kotlin에서의 사용 예시를 정리한 내용이다. 각각 삽입, 삭제, 접근 등의 대표적 연산을 예제로 포함하였다.

 

스택(Stack)

 

개념

LIFO(Last In, First Out) 구조: 마지막에 들어간 원소가 가장 먼저 나온다.

기본 연산:

push(삽입): 스택의 맨 위(top)에 원소를 추가

pop(삭제): 스택의 맨 위 원소를 제거하고 반환

peek(조회): 맨 위 원소를 제거하지 않고 반환

 

구현 및 사용 예제 (Kotlin)

 

일반적으로 Kotlin 표준 라이브러리에는 전용 Stack 클래스가 없으므로 MutableListArrayDeque를 사용한다. 여기서는 ArrayDeque를 스택처럼 사용해보겠다.

 

fun main() {

    val stack = ArrayDeque<Int>() // ArrayDeque를 사용해 스택처럼 활용



    // 삽입(push)

    stack.addLast(10)

    stack.addLast(20)

    stack.addLast(30)

    println("Stack after push: $stack") // [10, 20, 30]



    // 조회(peek)

    val top = stack.lastOrNull() // 가장 마지막 원소 확인

    println("Peek top element: $top") // 30



    // 삭제(pop)

    val popped = stack.removeLastOrNull() // 마지막 원소 제거 및 반환

    println("Popped element: $popped") // 30

    println("Stack after pop: $stack") // [10, 20]

}

 

큐(Queue)

 

개념

FIFO(First In, First Out) 구조: 먼저 들어간 원소가 먼저 나온다.

기본 연산:

enqueue(삽입): 큐의 뒤(rear)에 원소 추가

dequeue(삭제): 큐의 앞(front) 원소 제거 및 반환

peek(조회): 큐의 앞 원소를 제거하지 않고 반환

 

구현 및 사용 예제 (Kotlin)

 

Kotlin에서는 Queue를 구현할 때 ArrayDeque를 사용하는 경우가 많다. addLast()를 통해 삽입하고, removeFirst()를 통해 꺼낼 수 있다.

 

fun main() {

    val queue = ArrayDeque<String>()



    // 삽입(enqueue)

    queue.addLast("A")

    queue.addLast("B")

    queue.addLast("C")

    println("Queue after enqueue: $queue") // [A, B, C]



    // 조회(peek)

    val front = queue.firstOrNull()

    println("Peek front element: $front") // A



    // 삭제(dequeue)

    val dequeued = queue.removeFirstOrNull()

    println("Dequeued element: $dequeued") // A

    println("Queue after dequeue: $queue") // [B, C]

}

 

리스트(List)

 

개념

순서가 있는 원소들의 집합.

인덱스를 사용해 원소에 접근 가능.

불변 리스트(Immutable List)와 변경 가능한 리스트(Mutable List)가 존재.

기본 연산:

원소 접근: list[index]

삽입: MutableList의 경우 add()

삭제: MutableList의 경우 remove(), removeAt()

순회: for, forEach, map, filter 등 함수형 연산.

 

구현 및 사용 예제 (Kotlin)

 

fun main() {

    // 불변 리스트

    val immutableList = listOf(1, 2, 3)

    println("Immutable List: $immutableList") // [1, 2, 3]



    // 변경 가능한 리스트

    val mutableList = mutableListOf("Kotlin", "Java", "C++")



    // 접근

    println("Access element at index 1: ${mutableList[1]}") // Java



    // 삽입

    mutableList.add("Python")

    println("After add: $mutableList") // [Kotlin, Java, C++, Python]



    // 특정 위치에 삽입

    mutableList.add(1, "JavaScript")

    println("After insert at index 1: $mutableList") 

    // [Kotlin, JavaScript, Java, C++, Python]



    // 삭제

    mutableList.remove("C++")

    println("After remove 'C++': $mutableList")

    // [Kotlin, JavaScript, Java, Python]



    // 인덱스로 삭제

    mutableList.removeAt(2)

    println("After removeAt(2): $mutableList")

    // [Kotlin, JavaScript, Python]

}

 

해시맵(HashMap)

 

개념

Key-Value 쌍으로 데이터를 저장.

평균적으로 O(1) 접근, 삽입, 삭제 가능.

Key는 해싱을 통해 관리, 중복 Key 불가(덮어쓰거나 무시됨).

Kotlin에서는 HashMap, mutableMapOf(), mapOf() 등이 지원.

 

기본 연산

삽입(put): map[key] = value

접근(get): map[key] 또는 map.get(key)

삭제(remove): map.remove(key)

 

구현 및 사용 예제 (Kotlin)

 

fun main() {

    // 변경 가능한 맵 생성

    val hashMap = hashMapOf<String, Int>(

        "apple" to 3,

        "banana" to 5,

        "orange" to 2

    )



    // 접근

    println("Value for key 'banana': ${hashMap["banana"]}") // 5



    // 삽입 (없으면 추가, 있으면 업데이트)

    hashMap["grape"] = 10

    println("After put 'grape': $hashMap") 

    // {apple=3, banana=5, orange=2, grape=10}



    // 삭제

    hashMap.remove("orange")

    println("After remove 'orange': $hashMap")

    // {apple=3, banana=5, grape=10}



    // 키 존재 여부 확인

    println("Contains key 'apple'? ${"apple" in hashMap}") // true

    // 값 존재 여부 확인

    println("Contains value 5? ${hashMap.containsValue(5)}") // true



    // 순회

    for ((key, value) in hashMap) {

        println("$key: $value")

    }

}

정리

스택(Stack): LIFO 구조. ArrayDeque 등을 사용하여 addLast(), removeLast() 연산으로 구현.

큐(Queue): FIFO 구조. ArrayDeque 등을 사용하여 addLast(), removeFirst() 연산으로 구현.

리스트(List): 순서가 있는 원소 집합. listOf(), mutableListOf() 사용. 인덱스로 접근.

해시맵(HashMap): 키-값 구조. hashMapOf(), mutableMapOf() 사용. 평균 O(1) 접근/삽입/삭제.

 

이러한 기본 자료구조와 메서드들을 잘 익혀두면 알고리즘 문제 해결시 자료구조 선택이 쉬워지고, 시간 복잡도 고려에 도움이 된다.

반응형

'Kotlin' 카테고리의 다른 글

[Kotlin] Coroutine - Structured Concurrency  (0) 2024.01.12
[Kotlin] Coroutine의 예외처리  (0) 2024.01.12
[Kotlin] Coroutine - 취소  (0) 2024.01.11
[Kotlin] Coroutine - async()  (1) 2024.01.09
[Kotlin] Coroutine 디버깅 옵션  (1) 2024.01.09

블로그의 정보

Dev_TIMI

its_TIMI

활동하기