1
0

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 1 year has passed since last update.

Go言語 : キュー(Queue)

Last updated at Posted at 2022-10-09

キュー(Queue)

キューとは、入ってきたデータを順番に格納し、先に格納したデータから順に取り出すデータ構造。
先入れ先出し(FIFO:First-In First-Out)方式のデータ構造とも呼ばれる。

ライブラリ

今回使用したライブラリは、 "go-datastructures".
https://github.com/Workiva/go-datastructures

"go-datastructures”ライブラリのキューには、複数の型の値が入れられる。

インストール用コマンド
$ go get -u github.com/Workiva/go-datastructures/...

コード

package main

import (
	"fmt"
	"strconv"

	"github.com/Workiva/go-datastructures/queue"
)

func main() {

	// キューの作成
	var queueObj queue.Queue
	// 現在のキューの値 : []

	// キューへ値の追加
	queueObj.Put("AAA")
	queueObj.Put(111)
	queueObj.Put("BBB")
	queueObj.Put(222)
	queueObj.Put("CCC")
	queueObj.Put(333)
	// 現在のキューの値 :  ["AAA", 111, "BBB", 222, "CCC", 333]

	// キューから値を3つ取得
	qObj1, _ := queueObj.Get(int64(3))
	// 現在のキューの値 :  [222, "CCC", 333]

	// 出力
	fmt.Println("From Queue Value : " + qObj1[0].(string) + ", " + strconv.Itoa(qObj1[1].(int)) + ", " + qObj1[2].(string)) // From Queue Value : AAA, 111, BBB

	// キューから値を3つ取得
	qObj2, _ := queueObj.Get(int64(3))
	// 現在のキューの値 :  []

	// 出力
	fmt.Println("From Queue Value : " + strconv.Itoa(qObj2[0].(int)) + ", " + qObj2[1].(string) + ", " + strconv.Itoa(qObj2[2].(int))) // From Queue Value : 222, CCC, 333

	// キューの値チェック
	if queueObj.Empty() {
		fmt.Println("Queue Object is Empty.") // Queue Object is Empty.
	} else {
		fmt.Println("Queue Object is not Empty.")
	}
	// 現在のキューの値 :  []

	// キューへ値の追加
	queueObj.Put("DDD")
	queueObj.Put(444)
	queueObj.Put("EEE")
	queueObj.Put(555)
	// 現在のキューの値 :  ["DDD", 444, "EEE", 555]

	// キューの値チェック
	if queueObj.Empty() {
		fmt.Println("Queue Object is Empty.")
	} else {
		fmt.Println("Queue Object is not Empty.") // Queue Object is not Empty.
	}
	// 現在のキューの値 :  ["DDD", 444, "EEE", 555]

	// キューから値を2つ取得
	qObj3, _ := queueObj.Get(int64(2))
	// 現在のキューの値 :  ["EEE", 555]

	// 出力
	fmt.Println("From Queue Value : " + qObj3[0].(string) + ", " + strconv.Itoa(qObj3[1].(int))) // From Queue Value : DDD, 444
}

出力サンプル

$ go run queue.go
From Queue Value : AAA, 111, BBB
From Queue Value : 222, CCC, 333
Queue Object is Empty.
Queue Object is not Empty.
From Queue Value : DDD, 444

$ go build -o queue queue.go
$ ./queue
From Queue Value : AAA, 111, BBB
From Queue Value : 222, CCC, 333
Queue Object is Empty.
Queue Object is not Empty.
From Queue Value : DDD, 444

GitHub

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?