본문 바로가기
Fundamental/Data Structure

스택 Stack (kotlin Implementation ),코틀린 구현

by Derricks2 2021. 10. 31.
반응형

스택(stack)은 제한적으로 접근할 수 있는 나열 구조이다. 그 접근 방법은 언제나 목록의 끝에서만 일어난다. 끝먼저내기 목록(Pushdown list)이라고도 한다.

스택은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조(LIFO - Last In First Out)으로 되어 있다. 자료를 넣는 것을 '밀어넣는다' 하여 푸쉬(push)라고 하고 반대로 넣어둔 자료를 꺼내는 것을 (pop)이라고 하는데, 이때 꺼내지는 자료는 가장 최근에 푸쉬한 자료부터 나오게 된다. 이처럼 나중에 넣은 값이 먼저 나오는 것을 LIFO 구조라고 한다

 

Kotlin Implmentaion 

class MutableStack<E>(vararg items: E) {              // 1

  private val elements = items.toMutableList()

  fun push(element: E) = elements.add(element)        // 2

  fun peek(): E = elements.last()                     // 3

  fun pop(): E = elements.removeAt(elements.size - 1)

  fun isEmpty() = elements.isEmpty()

  fun size() = elements.size

  override fun toString() = "MutableStack(${elements.joinToString()})"
}

 

  • Inside the generic class, E can be used as a parameter like any other type.(E 제네릭 Type 사용 , any other type 사용 가능)

실제 사용 예 

fun <E> mutableStackOf(vararg elements: E) = MutableStack(*elements)

fun main() {
  val stack = mutableStackOf(0.62, 3.14, 2.7)
  println(stack)
}

 

 

참고

 

Kotlin Playground: Edit, Run, Share Kotlin Code Online

 

play.kotlinlang.org

 

 

https://gist.github.com/superbderrick/0ca53682257e0ce44e8f9dc400eacf1a

반응형

'Fundamental > Data Structure' 카테고리의 다른 글

큐 Queue(kotlin Implementation ),코틀린 구현  (0) 2021.11.01