실제 데이터는 slice에 저장하고, slice operation을 사용하여 스택의 push, pop, top, empty여부 확인 구현할 수 있다.
Stack API의 디자인은 empty시 동작을 어떻게 나타낼 것인가에 답해야 하는데, 이 포스트에서는 C++의 standard template library에서처럼 empty시 stack 연산 수행의 동작을 보장하지 않는 형태로 디자인하였다.
type Stack struct {
S []interface{}
}
func (s *Stack) Push(item interface{}) {
s.S = append(s.S, item)
}
func (s *Stack) Top() interface{} {
return s.S[len(s.S) - 1]
}
func (s *Stack) IsEmpty() bool {
return len(s.S) == 0
}
func (s *Stack) Pop() {
s.S = s.S[:len(s.S) - 1]
}
댓글 없음:
댓글 쓰기