2
1

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でDeque(両端キュー)

Posted at
  • Golangの標準ライブラリにDeque両端キューが見つからなかったので自作した
  • sliceの先頭に追加する処理は(実装によるだろうが)遅かったので採用していない
package main

import (
	"fmt"
)

func newDeque() *deque {
	return &deque{}
}

type deque struct {
	prep []interface{}
	ap   []interface{}
}

func (d *deque) push(item interface{}) {
	d.ap = append(d.ap, item)
}

func (d *deque) unshift(item interface{}) {
	d.prep = append(d.prep, item)
}

func (d *deque) empty() bool {
	return len(d.ap) == 0 && len(d.prep) == 0
}

func (d *deque) pop() interface{} {
	lenap := len(d.ap)
	if lenap != 0 {
		v := d.ap[lenap-1]
		d.ap = d.ap[:lenap-1]
		return v
	}
	v := d.prep[0]
	d.prep = d.prep[1:]
	return v
}

func (d *deque) shift() interface{} {
	lenprep := len(d.prep)
	if lenprep != 0 {
		v := d.prep[lenprep-1]
		d.prep = d.prep[:lenprep-1]
		return v
	}
	v := d.ap[0]
	d.ap = d.ap[1:]
	return v
}

func main() {

	q := newDeque()

	for i := 1; i < 10; i++ {
		q.push(i)
	}
	for i := 1; i < 10; i++ {
		q.unshift(i)
	}
	q.push(-999)

	for !q.empty() {
		fmt.Println(q.pop())
	}

	for i := 1; i < 10; i++ {
		q.push(i)
	}
	for i := 1; i < 10; i++ {
		q.unshift(i)
	}
	q.push(-999)

	for !q.empty() {
		fmt.Println(q.shift())
	}
}
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?