๋ฐ๋ณต์(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)
}
}