Skip to content
This repository was archived by the owner on Jan 13, 2021. It is now read-only.

Latest commit

Β 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Β 
Β 

README.md

κ°œμš”

반볡자(Iterator) λŠ” 객체 μ§€ν–₯적 ν”„λ‘œκ·Έλž˜λ°μ—μ„œ λ°°μ—΄μ΄λ‚˜ 그와 μœ μ‚¬ν•œ 자료 ꡬ쑰의 λ‚΄λΆ€μ˜ μš”μ†Œλ₯Ό 순회(traversing)ν•˜λŠ” 객체이닀.

λ‹€λ₯Έμ΄λ¦„

Cursor

동기

List λ“± μ§‘ν•© 객체(aggregate object)듀은 이 λ‚΄λΆ€ ν‘œν˜„ ꡬ쑰λ₯Ό λ…ΈμΆœν•˜μ§€ μ•Šκ³ λ„ μžμ‹ μ˜ μ›μ†Œλ₯Ό μ ‘κ·Όν•  수 μžˆλŠ” 방법을 μ œκ³΅ν•˜λŠ”κ²Œ μ’‹λ‹€. μΆ”κ°€μ μœΌλ‘œ, 이미 μ •μ˜λœ 방법과 λ‹€λ₯Έ λ°©μ‹μœΌλ‘œ μ›μ†Œλ“€μ„ μˆœνšŒν•˜κ³ μž ν•  μˆ˜λ„ μžˆλ‹€. ν•˜μ§€λ§Œ 순회 방법이 λ°”λ€Œμ—ˆλ‹€κ³  List Class의 Interfaceλ₯Ό λ³€κ²½ν•˜κ³  μ‹Άμ§€λŠ” μ•Šμ„κ²ƒμ΄λ‹€.

이런 문제λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•΄ λ§Œλ“€μ–΄μ§„ 것이 반볡자 νŒ¨ν„΄ 이닀. 이 νŒ¨ν„΄μ˜ 핡심은 List 객체에 μ ‘κ·Όν•΄μ„œ μƒˆλ‘œμš΄ λ‚΄μš©μ€ μ‚½μž…, μ‚­μ œ ν˜Ήμ€ μˆœνšŒν•˜λŠ” λ‚΄μš©μ„ 반볡자 객체에 μ •μ˜ν•˜λŠ” 것. 즉 반볡자 객체λ₯Ό λ‚˜νƒ€λ‚΄λŠ” Iterator ClassλŠ” μ›μ†Œλ“€μ— μ ‘κ·Όν•˜λŠ”λ° ν•„μš”ν•œ interfaceλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€. 즉 반볡자 κ°μ²΄λŠ” ν˜„μž¬ μ›μ†Œκ°€ 무엇인지 κ΄€λ¦¬ν•˜κ³ , 이미 λ°©λ¬Έν•œ μ›μ†Œλ“€μ΄ 무엇인지 μ•Œκ³  μžˆλ‹€.

ν™œμš©μ„±

반볡자 νŒ¨ν„΄μ€ 이런 λͺ©μ μœΌλ‘œ μ‚¬μš© λ©λ‹ˆλ‹€.

  • 객체 λ‚΄λΆ€ ν‘œν˜„ 방식을 λͺ¨λ₯΄κ³ λ„ μ§‘ν•© 객체의 각 μ›μ†Œλ“€μ— μ ‘κ·Όν•˜κ³  싢을 λ•Œ
  • μ§‘ν•© 객체λ₯Ό μˆœνšŒν•˜λŠ” λ‹€μ–‘ν•œ 방법을 μ§€μ›ν•˜κ³  싢을 λ•Œ
  • μ„œλ‘œ λ‹€λ₯Έ 객체 ꡬ쑰에 λŒ€ν•΄μ„œλ„ λ™μΌν•œ λ°©λ²•μœΌλ‘œ μˆœνšŒν•˜κ³  싢을 λ•Œ

μ˜ˆμ œμ½”λ“œ

class LinkedList<T> {
    private data class Node<T>(val nodeValue: T, var next: Node<T>? = null)
    private var head: Node<T>? = null

    fun insert(item: T) {
        if (head == null) head = Node(item)

        var cursor = head

        while (cursor?.next != null) {
            cursor = cursor.next
        }

        cursor?.next = Node(item)
    }

    fun forEach(action: (T) -> Unit) {
        var cursor = head
        while (cursor != null) {
            action(cursor.nodeValue)
            cursor = cursor.next
        }
    }
}

fun main() {
    val linkedList = LinkedList<Int>()
    linkedList.insert(1)
    linkedList.insert(2)
    linkedList.insert(3)
    linkedList.insert(4)
    linkedList.insert(5)

    linkedList.forEach {
        println(it)
    }
}