go stack구조 연습

chacha·2020년 7월 24일
0

go알고리즘

목록 보기
2/8

source

package main

import (
	"fmt"
)

func main() {
	stack := newStack()
	testValue := []int{1, 5, 3, 6, 7, 6, 5}

	for _, value := range testValue {
		stack.push(value)
	}

	for {
		value := stack.pop()
		if value == -1{
			break
		}
		fmt.Println(value)
	}
}

type Stack struct {
	s    []int
	size int
}

func newStack() *Stack {
	return &Stack{}
}

func (stack *Stack) push(v int) {
	stack.s = append(stack.s, v)
	stack.size++
}

func (stack *Stack) pop() int  {
	if stack.size == 0 {
		return -1
	}
	itemS, itemsS := stack.s[stack.size-1], stack.s[:stack.size-1]
	stack.s = itemsS

	stack.size--
	return itemS
}

output

5
6
7
6
3
5
1
profile
안녕하세요~ :)

0개의 댓글