article thumbnail image
Published 2022. 7. 19. 00:48

Stack

한 쪽 끝에서 자료를 넣고 뺄 수 있는 Last in First Out 자료 구조 형태를 말한다.  이는 상자에 물건을 넣고 빼는 것으로 비유할 수 있는데 나중에 상자에 넣은 물건은 먼저 넣은 물건의 위에 위치하게 되며 아래 있는 물건을 꺼내기 위해서는 위에 있는 물건들을 먼저 꺼내야 한다. 자료를 넣는 것을 ‘밀어넣는다’하여 푸쉬라고 하고 반대로 넣어둔 자료를 꺼내는 것을 팝이라고 하는데 이때 꺼내지는 자료는 가장 최근에 푸시한 자료부터 나오게 된다.

 

 

Stack 사용법

fun main(args : Array<String>) {
    val stack = Stack<Int>()

    //Stack에 데이터 추가
    stack.push(4)
    stack.push(3)
    stack.push(2)
    stack.push(1)

    //Stack에서 데이터 꺼내기
    println(stack.pop())

    //Stack의 최상단 값 출력
    println(stack.peek())

}

 

Stack - push 동작

push

stack.push(4)
stack.push(3)
stack.push(2)
stack.push(1)

이런 순서로 데이터를 스택에 추가했으면 pop() 메소드 4번 호출 시 4,3,2,1 순으로 데이터가 나오게 된다.

 

 

Stack - pop, clear 동작

pop

stack.push(4)
stack.push(3)
stack.push(2)
stack.push(1)
stack.pop() // stack에서 상단(4) 값 제거
stack.clear() // stack 전체 값 제거

 

 

Stack - peek 동작

peek

 

stack.push(3)
stack.push(2)
stack.push(1)
stack.peek() // stack에서 상단(3) 값 출력

 

 

Stack - 기타 메서드

stack.push(1)
stack.push(2)
stack.push(3)
stack.size // 크기 출력: 3
stack.empty() // stack 비어 있는 지 체크 (false)
stack.contains(1) // stack에 1이 있는 지 체크 (true)

 

 

 

참고

https://ko.wikipedia.org/wiki/%EC%8A%A4%ED%83%9D

'자료구조' 카테고리의 다른 글

Hash Table  (0) 2022.07.28
Queue  (0) 2022.07.16
복사했습니다!