8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Goでのスタックもただのスライス+appendで実装できる

Last updated at Posted at 2019-08-24

Goでのスタックもただのスライス+appendで実装できる

Goでのキューはただのスライス+appendで実装できるを見て、スライスでキューを実装できることに気づき、

type intQueue []int

func (queue *intQueue) enqueue(i int) {
	*queue = append(*queue, i)
}

func (queue *intQueue) dequeue() int {
	result := (*queue)[0]
	*queue = (*queue)[1:]
	return result
}

みたいなコードを書いて、

	var queue intQueue = make([]int, 0)
	queue.enqueue(0)
	for len(queue) != 0 {
		i := queue.dequeue()
		for _, j := range links[i] {
			if processed[j] {
				continue
			}
			results[j] += results[i]
			processed[j] = true
			queue.enqueue(j)
		}
	}

みたいに使っていたのだが、スタックもスライスで実装できることに気づいた.

package main

import (
	"fmt"
)

type intStack []int

func (stack *intStack) push(i int) {
	*stack = append(*stack, i)
}

func (stack *intStack) pop() int {
	result := (*stack)[len(*stack)-1]
	*stack = (*stack)[:len(*stack)-1]
	return result
}

func main() {
	var stack intStack = make([]int, 0)
	stack.push(1)
	stack.push(2)
	fmt.Println(stack.pop())
	stack.push(3)
	fmt.Println(stack.pop())
	fmt.Println(stack.pop())
}

実行してみた.

2
3
1

問題なさそう.

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?